c++ - 能够访问类定义之外的私有(private)对象成员

标签 c++

看来我的代码违反了不能在类定义之外访问对象的私有(private)成员的规则。

我有一个这样定义的类

class Test{
private:
    int x;
public:
    const Test& operator=(const Test &other){
        this->x = other.x;
        return *this;
    }
    void addX(int);
    void getX();
};

这里让我感到困惑的是,我能够访问类 Test 的对象“other”的私有(private)成员

这似乎不对,或者如果是,那一定是我遗漏了一些基本的东西

最佳答案

对于相同类型,您可以访问任何实例的私有(private)(和 protected )成员。这包括静态成员以及私有(private)或 protected 继承基。

几个例子:

class Base {
protected:
    int y;
private:
    int z;
};
class Sub;
class Test : private Base {
private:
    int x;
public:
    const Test& operator=(const Test &other) {
        this->x = other.x; // Can access private members for any instance
        this->y = other.y; // Can access a protected member of a base type
        this->z = other.z; // ERROR: Neither side is OK, can't access a private member of a base
        return *this;
    }
    void foo(Sub &sub);
};
class Sub : public Test
{
private:
    int w;
};
inline void Test::foo(Sub &sub) {
    int a = sub.x; // Still OK, as x is a member of Test
    a += sub.w; // ERROR: Can't access privates of subtypes however
}

关于c++ - 能够访问类定义之外的私有(private)对象成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696249/

相关文章:

c++ - weak_ptr 奇怪的复制构造函数

c++ - Makefile:如何正确包含头文件及其目录?

c++ - 无法将字符/字符串转换为 int

c++ - iOS 和 OpenCV 错误 : Assertion Failed in PhaseCorrelateRes

c++ - 计算 2 D3DXVECTOR3 与距离无关的 vector

c++ - 为带参数的函数转换 boost::array<float, 12> (const float (&arr)[12])

c++ - 关于循环变量优化的标准合规行为是什么?

C++:仅在未设置时设置 bool 值

c++ - 在双指针中赋值时出现段错误

c++ - Qt 5 的模型测试?