class CDemo{
public:
void SetValue(){ }
};
const CDemo Obj; // Obj 是常量对象
在 Obj 被定义为常量对象的情况下,下面这条语句是错误的,编译不能通过:
Obj.SetValue();错误的原因是,常量对象一旦初始化后,其值就再也不能更改。因此,不能通过常量对象调用普通成员函数,因为普通成员函数在执行过程中有可能修改对象的值。
#include<iostream>
using namespace std;
class Sample{
public:
void GetValue() const; //常成员函数
};
void Sample::GetValue() const //常成员函数
{
}
int main(){
const Sample o;
o.GetValue(); //常量对象上可以执行常量成员函数
return 0;
}
上面的程序在 Visual Studio 中没有问题,但在 Dev C++ 中,要为 Sample 类编写无参构造函数才可以。在 Dev C++ 中,常量对象如果使用无参构造函数初始化,就需要显式写出无参构造函数。
#include <iostream>
using namespace std;
class CTest{
private:
int n;
public:
CTest(){n = 1;}
int GetValue() const { return n; }
int GetValue() { return 2*n; }
};
int main(){
const CTest objTestl ;
CTest objTest2;
cout << objTestl.GetValue () << "," << objTest2.GetValue();
return 0;
}
程序的输出结果是:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有