如何访问通过引用operator = function传递的对象的私有数据?

Rıf*_*ran 1 c++ overloading private operator-keyword

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

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;
}
Run Code Online (Sandbox Code Playgroud)

Aar*_*aid 6

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

如果C++要更加严格,并限制private对同一实例中方法的访问,那么它实际上会说类型*thiso引用类型"更强大" .

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

(†)相同的类型,除了增加const,但这在这里并不重要.

  • 从语义上讲,`private`意味着它是类实现的一部分,只能通过类的实现来访问. (3认同)