问题
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