关于C++类的成员函数是否要加关键字“const”

时间:2022-02-22 19:49:02

原则:类的成员函数在小括号后大括号前加上 const ,代表不准备改变对象的数据。不加的话代表有可能会改变对象的数据。

1.当常量对象,就是加上const修饰的类的成员去调用常量成员函数时,这表示:对象的初始化数据一定不能改变,常量成员函数说:放心,我不会改变你的初始化数据的,这一切都很好。

2.当常量对象调用没加const修饰的类的成员函数时,这表示:对象的初始化数据一定不能改变,非常量成员函数说:我不能保证哦!完犊子,没商量好,这要出问题。

3.当非常量对象调用常量成员函数时,这表示:对象的初始化数据可以被改变,常量成员函数说:我并不打算改变你的数据。这,很和谐!

4.当非常量对象调用非常量成员函数时,这表示:对象的初始化数据可以被改变,非常量成员函数说:你调用我,我有可能会改变你的数据哦,这个对象说:改就改喽,我本来就没打算一辈子不改。嗯,气氛还挺好。

举例:

singledog.h头文件:

#pragma once
#include<iostream>
using namespace std;
class SingleDog
{
public:
SingleDog(int id, int age, const char* city);
int get_ID() const { return ID; }
int get_Age() const { return Age; }
const char* get_City() const { return City; }
void set_ID(int id) { ID = id; }
void play();
~SingleDog(); private:
int ID;
int Age;
const char* City;
}; SingleDog::SingleDog(int id,int age,const char* city):ID(id),Age(age),City(city)
{
cout << "构造函数被调用" << endl;
}
void SingleDog::play()
{
cout << "我喜欢打篮球" << endl;
} SingleDog::~SingleDog()
{
}

singledog.cpp源文件:

#include"singledog.h"
int main()
{
SingleDog sd1(, , "shanghai");
cout <<"Age: "<< sd1.get_Age() << endl;
cout << "ID: " << sd1.get_ID() << endl;
cout << "City: " << sd1.get_City() << endl; sd1.set_ID();
cout << "ID: " << sd1.get_ID() << endl; //***********************************************// const SingleDog sd2(, , "shanghai");
cout << "Age: " << sd2.get_Age() << endl;
cout << "ID: " << sd2.get_ID() << endl;
cout << "City: " << sd2.get_City() << endl; //sd2.set_ID(456);//注意,常量对象调用非常量成员函数了,这一句调用会出错!!!
cout << "ID: " << sd1.get_ID() << endl; system("pause");
return ;
}

小结:设计类的成员函数时,只要不准备改变对象的数据,就加上const去修饰。一出手就要不凡。(侯捷老师的话,哈哈哈)