繁体   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