struct和class区别
- 在C++中struct和class唯一的区别就在于 默认的访问权限不同
- 区别:
- struct默认访问权限为公共
- class默认访问权限为私有
成员属性设置为私有
优点1:将所有属性设置为私有,可以自己控制读写权限
优点2:对于读写权限,我们可以检测数据的有效性
示例:
#include <iostream>#include <string>using namespace std;class Person {public: //设置姓名 void setName(string name) { this->name = name; } // 获取姓名 string getName() { return this->name; } // 设置年龄,检测年龄的有效性 void setAge(int age) { if (age < 0 || age > 150) { this->age = 0; cout << "输入有误!" << endl; return; } this->age = age; } // 获取年龄 int getAge() { return this->age; } // 设置情人 void setLover(string lover) { this->lover = lover; }private: // 姓名 string name; // 读写权限 //年龄 int age = 20; // 只读权限 // 情人 string lover; // 只写权限};int main(void) { Person p1; p1.setName("张三"); p1.setAge(20); int age = p1.getAge(); string name = p1.getName(); p1.setLover("小三"); cout << "姓名:" << name << " 年龄:" << age << endl; return 0;}