面向对象编程
学习C++中的封装、继承和多态特性
60%
封装
继承
多态
练习例题
封装基础
访问修饰符
控制类成员的访问权限,实现数据隐藏和接口暴露。
class Student {
private: // 私有成员,只能在类内部访问
string name;
int age;
protected: // 保护成员,可以在派生类中访问
int score;
public: // 公有成员,可以在类外部访问
// 构造函数
Student(string n, int a) : name(n), age(a), score(0) {}
// 公有接口方法
void setName(string n) {
name = n; // 通过公有方法访问私有成员
}
string getName() const {
return name;
}
void setAge(int a) {
if (a > 0 && a < 150) { // 数据验证
age = a;
}
}
int getAge() const {
return age;
}
};
// 类的使用
int main() {
Student s("张三", 20);
s.setName("李四"); // 正确:通过公有方法访问私有成员
// s.name = "王五"; // 错误:私有成员不能直接访问
cout << s.getName() << endl;
}
- 提高代码的安全性,防止数据被非法访问
- 隐藏实现细节,提供简单的接口
- 可以对数据进行验证,保证数据的有效性
构造函数和析构函数
对象的创建和销毁机制。
class Rectangle {
private:
double width;
double height;
public:
// 默认构造函数
Rectangle() : width(0), height(0) {
cout << "默认构造函数被调用" << endl;
}
// 带参数的构造函数
Rectangle(double w, double h) : width(w), height(h) {
cout << "带参构造函数被调用" << endl;
}
// 拷贝构造函数
Rectangle(const Rectangle& other) : width(other.width), height(other.height) {
cout << "拷贝构造函数被调用" << endl;
}
// 析构函数
~Rectangle() {
cout << "析构函数被调用" << endl;
}
// 移动构造函数(C++11)
Rectangle(Rectangle&& other) noexcept
: width(other.width), height(other.height) {
other.width = 0;
other.height = 0;
cout << "移动构造函数被调用" << endl;
}
};
int main() {
Rectangle r1; // 调用默认构造函数
Rectangle r2(3.0, 4.0); // 调用带参构造函数
Rectangle r3 = r2; // 调用拷贝构造函数
Rectangle r4 = std::move(r1);// 调用移动构造函数
}