why copy constructor use private property directly in C++

岁酱吖の 提交于 2019-12-12 06:23:24

问题


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:

'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.


回答1:


It won't compile, because your function is not declared const:

int getFreq() const; // accessor function that does not modify the object

Thus, you can not call it with const instance: 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).



来源:https://stackoverflow.com/questions/33844477/why-copy-constructor-use-private-property-directly-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!