#include2.类和结构体区别#include using namespace std; //访问权限 //public 公共权限 类内可以访问 类外可以访问 //protected 保护权限 类内可以访问 类外不可以访问 //private 私有权限 类内可以访问 类外不可以访问 //注意protected 和 private的区别主要体现在继承,继承后子类可以访问父类的protected,但是不可以访问private class Person { //公共权限 public: string m_Name; //保护权限 protected: string m_Car; //私有权限 private: int m_ID; public: //类内访问 void initializing() { m_Name = "xiaoliyu"; m_Car = "BMW"; m_ID = 123456; } //类内访问 void showInfo() { cout< Person p; //类外访问public p.initializing(); p.showInfo(); //类外访问protected //p.m_Car = "Benz";//“Person::m_Car”: 无法访问 protected 成员(在“Person”类中声明) //类外访问protected //p.m_ID = 235689;//error C2248: “Person::m_ID”: 无法访问 private 成员(在“Person”类中声明) return 0; }
#include3.成员属性私有化#include using namespace std; class C { int m_ID ;//默认是私有权限 //static const int m_ID = 10;//error C2864: “C::m_ID”: 只有静态常量整型数据成员才可以在类中初始化 }; struct S { //int m_ID;//默认是公共权限 static const int m_ID = 10;//error C2864: “S::m_ID”: 只有静态常量整型数据成员才可以在类中初始化 }; int main() { C c; //c.m_ID = 20;//error C2248: “C::m_ID”: 无法访问 private 成员(在“C”类中声明) S s; //s.m_ID = 20;//可以正常访问 return 0; }
成员设置为私有化
1.可以自身控制读写权限
2.对于写可以检测数据的有效性
#include#include using namespace std; class Person { public: //m_name //写入 void setName(string name) { m_Name = name; } //读取 string getName() { return m_Name; } //m_Age //写入 void setAge(int age) { if (age < 0 || age > 100) { return; } m_Age = age; } //读取 int getAge() { return m_Age; } //m_ID //写入 void setID(int id) { m_ID = id; } //变量均设置为私有权限 private: string m_Name;//可以读写 int m_Age;//可以读,可以有条件的写 string m_ID;//可以写 }; int main() { Person p; //读写 p.setName("xiaoliyu"); cout<



