【问题标题】:How do i access the private data of an object which is passed by reference to operator= function?如何访问通过引用传递给 operator= 函数的对象的私有数据?
【发布时间】:2015-07-12 12:18:38
【问题描述】:

我想知道如何访问通过引用或值传递的对象的私有数据?此代码有效。为什么?我需要一些解释。

class test_t {
    int data;
public:
    test_t(int val = 1): data(val){}
    test_t& operator=(const test_t &);
};

test_t& test_t::operator=(const test_t & o){
    this->data = o.data;
    return *this;
}

【问题讨论】:

标签: c++ overloading private operator-keyword


【解决方案1】:

private 表示test_t 类的所有实例都可以看到彼此的私有数据。

如果 C++ 更严格,并限制 private 访问同一实例中的方法,这实际上是说 *this 的类型比 o 引用的类型“更强大” .

*this 的类型与o 的类型相同(†),即test_t &,因此o 可以做任何*this 可以做的事情。

(†) 相同的类型,除了添加const,但这并不重要。

【讨论】:

  • 从语义上讲,private表示它是类实现的一部分,只能被类的实现访问。
猜你喜欢
  • 2012-02-03
  • 2012-03-03
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 2014-11-16
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多