鱼C论坛

 找回密码
 立即注册
查看: 1169|回复: 0

[技术交流] 004 - 类和对象(class & object)③ 类成员函数(Class Function)

[复制链接]
发表于 2020-5-8 16:16:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 liuzhengyuan 于 2020-5-8 17:09 编辑

待更新
C++ 自学心得 |004 - 类和对象(class & object)③ 类成员函数(Class Function)





类的成员函数是指那些把定义和原型写在类定义内部的函数,就像类定义中的其他变量一样。类成员函数是类的一个成员,它可以操作类的任意对象,可以访问对象中的所有成员。


P.S.:这个应该不算特别难(直接上代码)

如果想统计一个学生的成绩并输出,可以这样↓
  1. #include<bits/stdc++.h>
  2. using namespace std;

  3. class Exam {
  4.         public:
  5.                 string student_name;
  6.                 int score;
  7.                
  8.                 Exam(string aname, int ascore)
  9.                 {
  10.                         student_name = aname;
  11.                         score = ascore;
  12.                 }
  13. };

  14. int main()
  15. {
  16.         Exam first("A", 98);
  17.        
  18.         cout << first.student_name << "考了" << first.score << "分";
  19. }
复制代码

效果:
  1. A考了98分
复制代码





可以使用类成员函数来判断 A 同学是否及格
  1. #include<bits/stdc++.h>
  2. using namespace std;

  3. class Exam {
  4.         public:
  5.                 string student_name;
  6.                 int score;
  7.                
  8.                 Exam(string aname, int ascore)
  9.                 {
  10.                         student_name = aname;
  11.                         score = ascore;
  12.                 }
  13.                
  14.                 bool ispass()
  15.                 {
  16.                         if (score >= 60)
  17.                         {
  18.                                 return true;
  19.                         }
  20.                         return false;
  21.                 }
  22. };

  23. int main()
  24. {
  25.         Exam first("A", 98);
  26.        
  27.         cout << first.ispass();
  28. }
复制代码

效果:
  1. 1
复制代码




下一篇:???

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-22 09:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表