C++:常函数和常对象

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:43   1633   0
#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
 Person(int age, float score)
 {
  this->age = age;
  this->score = score;
 }
 
 // 常函数:修饰成员函数中的this指针,使this指针指向的值也不可修改。
 // 常函数在函数声明和函数定义时都须加上const关键字。
 void showPerson() const
 {
  // this->age = 100; // (错误代码)常函数中this指针指向的值不可修改。
  // this指针的本质:Person* const this(指向Person的指针常量),指针的指向不可以修改,指针指向的值可以修改。
  this->score = 99; // score 已加mutable修饰,可以在常函数中修改。
  cout<<"Age = "<<this->age<<endl;
  cout<<"Score = "<<this->score<<endl;
 }
 
 void change()
 {
  //this->age = 100;
  this->score = 99.0;
 }

private:
 int age;
 // 常函数、常对象中某些特殊的属性需修改,可先用mutable关键字修饰该属性
 mutable float score; 
};

void test01()
{
 Person p1(18, 90.0);
 p1.showPerson();
}

void test02()
{
 /* 常对象 - 该对象在其生命周期内,其所有的数据成员的值都不能修改(mutable关键字修饰的除外)
   1、常对象只能调用常函数,不能调用普通成员函数,常函数是常对象唯一对外接口;
   2、常对象在定义是须初始化。
 */
 const Person p1(18, 90.0);
 // p1.change(); // (错误代码)常对象只能调用常函数。
 p1.showPerson(); // 常对象调用常函数。
}

int main()
{
 //test01();
 test02();
 return 0;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP