能够在类定义之外访问私有对象成员

Able to access private object member outside of class definition

本文关键字:访问 对象 成员 定义      更新时间:2023-10-16
似乎

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

我有一个这样的类定义

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

让我感到困惑的是,我能够访问类测试的对象"其他"的私人成员

这似乎不对,或者如果是,我一定缺少一些基本的东西

您可以访问同一类型的任何实例的私有(和受保护(成员。这包括静态成员以及私有或受保护的继承基。

举几个例子:

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++标准规定的方式。但是,我同意这可能不是您所期望的。

为了解决这个问题,您可能需要记住访问检查是编译时检查 - 它们在程序编译时发生,而不是在执行时发生。

现在,让我们考虑一下您的示例:

const A& operator=(const A& a) {
    x = a.x;
    return *this;
}

现在,在编译此函数时,编译器(通常,让我们假装内联没有发生(无法知道A&是否与this对象相同,因为它可以称为

A a;
a = a;

底线 - 即使我们愿意,我们也将无法使访问修饰符检查考虑类实例。

如cpp首选项中所述

的私有成员只能由该类的成员和好友访问,无论成员是位于相同实例还是不同实例上:

class S { private: int n; // S::n is private public: S() : n(10) {} // this->n is accessible in S::S S(const S& other) : n(other.n) {} // other.n is accessible in S::S };