![](/img/trans.png)
[英]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.