马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 liuzhengyuan 于 2020-5-8 17:09 编辑
待更新
C++ 自学心得 |004 - 类和对象(class & object)③ 类成员函数(Class Function)
类的成员函数是指那些把定义和原型写在类定义内部的函数,就像类定义中的其他变量一样。类成员函数是类的一个成员,它可以操作类的任意对象,可以访问对象中的所有成员。
P.S.:这个应该不算特别难(直接上代码)
如果想统计一个学生的成绩并输出,可以这样↓
- #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 << "分";
- }
复制代码
效果:
可以使用类成员函数来判断 A 同学是否及格:
- #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;
- }
-
- bool ispass()
- {
- if (score >= 60)
- {
- return true;
- }
- return false;
- }
- };
- int main()
- {
- Exam first("A", 98);
-
- cout << first.ispass();
- }
复制代码
效果:
下一篇:??? |