[英]Why use private copy constructor vs. deleted copy constructor in C++
[英]why copy constructor use private property directly in C++
看以下内容:
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
是一个私有成员,更有意义的是我们应该使用接口getFreq
来访问它。
它不会编译,因为您的函数未声明为const
:
int getFreq() const; // accessor function that does not modify the object
因此,您不能使用const
实例来调用它: const node &obj
。
访问obj.freq
,因为它适应const
实例,从而使obj.freq
不可修改-用成员函数执行此操作是无稽之谈(缺少const
说明符的成员函数中的代码可能(并且应该)需要可修改的实体)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.