使用
const
关键字修饰的函数为常成员函数,常成员函数声明的格式如下:
类型说明符 函数名(参数表) const;
#include <iostream>
using namespace std;
class Test{
private:
int t1, t2;
public:
Test(int t1, int t2) : t1(t1), t2(t2){}
void print();
void print() const;
};
void Test::print(){
cout << t1 << ":" << t2 << endl;
}
void Test::print() const { // const修饰的常函数
cout << t1 << ":" << t2 << endl;
}
int main(){
Test *test1 = new Test(6, 9);
test1 -> print(); // 调用 void print()
const Test *test2 = new Test(1, 2021);
test2 -> print(); // 调用 void print() const
delete test2;
delete test1;
return 0;
}
-
是函数类型的一个组成部分,因此在函数的定义部分也要带const
关键字。const
- 无论是否通过常对象调用常成员函数,在常成员函数调用期间,目的对象都被视同为常对象,因此常成员函数不能更新目的的对象的数据成员,也不能针对目的对象调用该类中没有用
修饰的成员函数。const
-
关键字可以用于对重载函数的区分。const
- 如果将一个对象说明为常对象,则通过该常对象只能调用它的常成员函数,而不能调用其他成员函数。