类和对象
C++面向对象的三大特性为:封装、继承、多态
C++认为万事万物都皆为对象,对象上有其属性和行为
封装的意义
封装是C++面向对象三大特性之一
封装的意义:
- 将属性和行为作为一个整体,表现生活中的事物
将属性和行为加以权限控制
语法:class 类名{访问权限:属性/行为;#include<iostream> #include<cmath> using namespace std; #define PI 3.14 class Circle { public: int m_r; double calculateZC() { return 2 * PI * m_r; } }; int main() { Circle c1; c1.m_r = 5; cout << c1.calculateZC(); return 0; }
访问权限
| 权限 | 行为 |
|---|---|
| 公共权限 | 类内可以访问,类外可以访问 |
| 保护权限 | 类内可以访问,类外不可以访问 |
| 私有权限 | 类内可以访问,类外不可以访问 |
保护权限和私有权限的区别是,保护权限的属性,子类可以访问,私有权限的属性,子类不能访问。
struct和class的区别
在C++中struct和class唯一的区别就在于默认的访问权限不同
区别:
- struct默认权限为公共
class默认权限为私有
#include<iostream> #include<cmath> #include<string> using namespace std; #define PI 3.14 class C1 { int m_A = 10; }; struct C2 { int m_A = 10; }; int main() { C1 c1; // c1.m_A = 20; 报错,不可访问 C2 c2; c2.m_A = 20; return 0; }
成员属性设置为私有
优点1:将所有成员属性设置为私有,可以自已控制读写权限
优点2:对于写权限,我们可以检测数据的有效性
#include<iostream>
#include<string>
using namespace std;
class Person {
private:
string name;
int age = 18;
string idol;
public:
void setname(string name) {
if (name.length() < 7 && name.length() > 1) {
this->name = name;
}
else {
cout << "名字长度不符合标准" << endl;
}
}
string getname() {
return name;
}
int getage() {
return age;
}
void setidol(string idol) {
this->idol = idol;
}
};
int main()
{
Person p1;
p1.setname("张三四五");
p1.setname("张三");
cout << p1.getname() << endl;
cout << p1.getage() << endl;
p1.setidol("小明");
string s = "张三";
return 0;
}将所有成员变量设置为私有,我们可以人为的选择暴露一些接口,让用户可以读或写某些成员变量。
并且对于写可以进行校验,例如用户通过接口传入名字时,我们可以检测名字是否过长或过短。符合条件才会执行写操作。