簡體   English   中英

為什么復制構造函數直接在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM