请看以下内容:
class node
{
int freq;
public:
node(const node &other)
{
freq = other.freq;
}
int getFreq()
{
return freq;
}
};
效果很好。但是,当我用 freq = obj.getFreq()
替换 freq = obj.freq
时,它会给我这个错误:
'int node::getFreq(void)': cannot convert 'this' pointer from 'const node' to 'node &'
为什么? freq
是一个私有(private)成员,我们应该使用接口(interface) getFreq
来访问它更有意义。
最佳答案
它不会编译,因为你的函数没有声明const
:
int getFreq() const; // accessor function that does not modify the object
因此,您不能使用 const
实例调用它:const node &obj
。
访问 obj.freq
是可行的,因为它适应了 const
实例,使得 obj.freq
不可修改 - 使用成员函数将是无稽之谈(缺少 const
说明符的成员函数内的代码可能(并且应该)需要可修改的实体)。
关于c++ - 为什么复制构造函数在C++中直接使用私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844477/