马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 liuzhengyuan 于 2020-7-6 12:50 编辑
待更新
C++ 自学心得 |005 - 类和对象 ④ private & pubilc 关键字 + getter & setter
大概总结了一下
关键字 | 含义 | public | 成员可以在类外部被访问 | private | 成员只可以在类内部被访问 | protect | 可以在派生类(即子类)被访问 |
1,getter & setter
- #include<bits/stdc++.h>
- using namespace std;
- class Exam {
- public:
- string student_name;
- int score;
-
- Exam(string aname, int ascore)
- {
- student_name = aname;
- score = ascore;
- }
- };
- int main()
- {
- Exam first("A", 98);
-
- cout << first.student_name << "考了" << first.score << "分";
- }
复制代码
但是也会有人乱改分数比如:
300分……
防止乱改分数的人的最有效方法就是 getter and setter
先说说 private 关键字
不妨把刚刚的代码改成:
score 变量是 Exam 类私有的
所以主函数访问不了 score 变量,所以报错…… - #include<bits/stdc++.h>
- using namespace std;
- class Exam {
- public:
- string student_name;
-
- Exam(string aname, int ascore)
- {
- student_name = aname;
- score = ascore;
- }
-
- private:
- int score;
- };
- int main()
- {
- Exam first("A", 98);
-
- cout << first.student_name << "考了" << first.score << "分";
- }
复制代码
结果是:
getter & setter 代码
乱设置分数的,最后都会被强制设置为 0 分
- #include<iostream>
- using namespace std;
- class Students {
- private:
- int score;
- public:
- string name;
-
- Students(string aname, int ascore)
- {
- name = aname;
- setscore(ascore);
- }
-
- bool ispass()
- {
- if(score<60)
- {
- return false;
- }
- return true;
- }
-
- void setscore(int ascore)
- {
- if(ascore<0 || ascore>100)
- {
- score = 0;
- }
- else
- {
- score = ascore;
- }
- }
-
- int getscore()
- {
- return score;
- }
- };
- int main()
- {
- Students Andy("^_^",300);
- cout<<Andy.getscore();
-
- return 0;
- }
复制代码
下一篇:? ? ? |