类和对象

三大特性:封装,继承,多态

封装

 #include"methodState.h"class Student {
 public:
     string name;
     string id;
     void setName(string name) {
         this->name = name;
     }
     void setId(string id) {
         this->id = id;
     }
     string getName() {
         return this->name;
     }
     string getId() {
         return this->id;
     }
     void show() {
         cout << "姓名:" << getName() << endl;
         cout << "学号:" << getId() << endl;
     }
 };
 int main() {
 ​
     Student stu1, stu2;
     stu1.setId("20210201");
     stu1.setName("小明");
     stu2.setId("20210202");
     stu2.setName("小花");
     stu1.show();
     stu2.show();
 ​
     system("pause");
     return 0;
 }

 

权限

  • public:类内可以访问,类外可以访问

  • protected:类内可以访问,类外不可以访问,子类可以调用父类私有属性

  • private:类内可以访问,类外不可以访问,子类不可以调用父类私有属性

struct与class区别

struct默认权限为public,class默认权限为private

尽管结构体可以包含成员函数,但很少这样做,所以通常情况结构体只会声明成员变量,结构体声明通常不包含public或private访问修饰符

 //用指针绕过私有权限操纵属性
 class Student {
 private:
     int id;
 public:
     int getId() {
         return this->id;
     }
     void show() {
         cout << "学号:" << getId() << endl;
     }
 };
 int main() {
     Student stu1;
     int* p;
     p = (int*)&stu1;
     *p = 22;
     stu1.show();
 ​
     system("pause");
     return 0;
 }

 

参考链接:指针修改私有属性

P103.7:24

posted on 2021-11-23 16:56  托马斯源  阅读(26)  评论(0编辑  收藏  举报