【问题标题】:why copy constructor use private property directly in C++为什么复制构造函数在 C++ 中直接使用私有属性
【发布时间】: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


【解决方案1】:

它不会编译,因为你的函数没有声明const:

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

因此,您不能使用const 实例调用它:const node &obj。

访问obj.freq 有效,因为它适应const 实例,使obj.freq 不可修改 - 使用成员函数执行此操作将是无稽之谈(成员函数内部的代码缺少const 说明符可能(并且应该)需要可修改的实体)。

【讨论】:

  • 你能看看这个问题吗:stackoverflow.com/questions/33847779/…
  • 访问obj.freq 有效,实际上是因为node 类是其自身的朋友类。你可以改变你的答案。
  • 不,不是吗? “freq 是私人成员” - 你在问题中。
  • 是的,freq 是私有成员。但是节点类的朋友类可以访问节点类的私有成员,节点类是自己的朋友类。
  • 你知道friend关键字,这很好,但在这里提它没有意义。这完全是关于没有 const 说明符的成员函数与非常量成员数据,仅此而已。
猜你喜欢
  • 2011-01-26
  • 2016-10-13
  • 2015-11-02
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 2014-04-12
相关资源
最近更新 更多