[英]why copy constructor use private property directly in C++
Look at following: 看以下内容:
class node
{
int freq;
public:
node(const node &other)
{
freq = other.freq;
}
int getFreq()
{
return freq;
}
};
It works well. 它运作良好。 However, when I replace
freq = obj.freq
with freq = obj.getFreq()
, it gives me this error: 但是,当我用
freq = obj.getFreq()
替换freq = obj.freq
时,它给了我这个错误:
'int node::getFreq(void)': cannot convert 'this' pointer from 'const node' to 'node &'
Why? 为什么?
freq
is a private member, it makes more sense that we should use the interface getFreq
to access it. freq
是一个私有成员,更有意义的是我们应该使用接口getFreq
来访问它。
It won't compile, because your function is not declared const
: 它不会编译,因为您的函数未声明为
const
:
int getFreq() const; // accessor function that does not modify the object
Thus, you can not call it with const
instance: const node &obj
. 因此,您不能使用
const
实例来调用它: const node &obj
。
Accessing obj.freq
works, because it adapts to the const
instance, making obj.freq
not modifiable - to do this with a member function would be a nonsense (code inside member function lacking const
specifier might (and should) require modifiable entities). 访问
obj.freq
,因为它适应const
实例,从而使obj.freq
不可修改-用成员函数执行此操作是无稽之谈(缺少const
说明符的成员函数中的代码可能(并且应该)需要可修改的实体)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.