看来我的代码违反了不能在类定义之外访问对象的私有(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/