【发布时间】:2016-02-23 23:47:21
【问题描述】:
看下面:
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 来访问它更有意义。
【问题讨论】:
-
不,在构造函数初始化列表中直接访问数据成员更有意义。否则,您必须为每个数据成员提供 getter 才能复制对象。
-
另外,您的标题与您提出的问题不符。
-
@LightnessRacesinOrbit
'int node::getFreq(void)': cannot convert 'this' pointer from 'const node' to 'node &' -
在问题中......
标签: c++ function class constructor