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

How do i access the private data of an object which is passed by reference to operator= function?

本文关键字:function operator 对象 数据 访问 何访问 引用      更新时间:2023-10-16

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

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;
}

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

如果c++更严格,并且限制private对同一实例中的方法的访问,那么它将有效地说*this的类型比o引用的类型"更强大"。

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

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