方法(成员函数)
本课属于 Coddy C++ 学习旅程的“面向对象编程”单元。第 8 课,共 104 课。
成员函数定义了对象可以执行的操作。它们有返回类型、名称和可选参数。
返回值的方法
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};void 方法(无返回值)
class Printer {
public:
void printMessage(std::string msg) {
std::cout << msg << std::endl;
}
};返回 bool 的方法
class Checker {
public:
bool isPositive(int num) {
return num > 0;
}
};在头文件中声明,在源文件中实现
// Calculator.h
class Calculator {
public:
int add(int a, int b);
};
// Calculator.cpp
int Calculator::add(int a, int b) {
return a + b;
}返回类型写在方法名前面。如果方法不返回任何内容,就使用 void。:: 作用域解析运算符将实现与其所属的类关联起来。
挑战
中等为 StringHelper 类实现 4 个成员函数,它们的返回类型和参数各不相同:
getLength():返回int,表示文本的长度toUpperCase():返回std::string,表示大写形式的文本contains(std::string word):返回bool,表示文本是否包含该单词repeat(int times):返回std::string,表示用空格分隔的重复文本
亲手试试
#include <iostream>
#include "StringHelper.h"
int main() {
std::string input;
std::getline(std::cin, input);
StringHelper helper;
helper.text = input;
std::cout << "Original: " << helper.text << std::endl;
std::cout << "Length: " << helper.getLength() << std::endl;
std::cout << "Uppercase: " << helper.toUpperCase() << std::endl;
std::cout << "Contains 'World': " << (helper.contains("World") ? "yes" : "no") << std::endl;
std::cout << "Repeated: " << helper.repeat(3) << std::endl;
return 0;
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: C++ 在线编译器