课程进度 57% · 第11/18章第11/18章 · 标签 1/3
— 1 —
访问修饰符
控制类成员的访问权限,实现数据隐藏和接口暴露。
cpp
1
class Student {
2
private:
3
string name;
4
int age;
5
protected:
6
int score;
7
public:
8
Student(string n, int a)
9
: name(n), age(a), score(0) {}
10
11
void setName(string n) { name = n; }
12
string getName() const { return name; }
13
14
void setAge(int a) {
15
if (a > 0 && a < 150) age = a;
16
}
17
int getAge() const { return age; }
18
};
19
20
int main() {
21
Student s("张三", 20);
22
s.setName("李四");
23
// s.name = "王五"; // 错误!
24
cout << s.getName() << endl;
25
}
📖封装的优点:提高安全性,隐藏实现细节,提供简单接口,可对数据进行验证
— 2 —
构造函数与析构函数
cpp
1
class Rectangle {
2
double width, height;
3
public:
4
Rectangle()
5
: width(0), height(0) {}
6
Rectangle(double w, double h)
7
: width(w), height(h) {}
8
9
// 拷贝构造函数
10
Rectangle(const Rectangle& other)
11
: width(other.width),
12
height(other.height) {}
13
14
// 移动构造函数(C++11)
15
Rectangle(Rectangle&& other) noexcept
16
: width(other.width),
17
height(other.height) {
18
other.width = 0;
19
other.height = 0;
20
}
21
22
// 析构函数
23
~Rectangle() {}
24
25
double area() const { return width * height; }
26
};