能够在类定义之外访问私有对象成员
Able to access private object member outside of class definition
似乎
我的代码违反了不能在类定义之外访问对象的私有成员的规则。
我有一个这样的类定义
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 };
相关文章:
- 使用迭代器时如何访问对象在向量中的位置?
- 无法通过指针访问对象的成员
- 如何从传递到对象的对象内部访问对象的类属性?
- 有没有办法在C++中循环访问对象的不同数据成员
- 如何访问对象动态数组中的私有成员变量?
- c++ 循环访问对象列表并删除对象
- 循环访问对象列表 c++
- 访问对象的取消引用值的语法
- 如何访问对象的成员变量的取消引用值
- C++:访问对象内部子对象的方法
- 如果访问对象,则指向的对象内部的指针会更改内存位置
- 是否可以从 C++ 中的构造函数访问对象名称?
- 仅允许访问对象的成员,而不允许访问对象本身
- 从地图访问对象会导致新对象C 的实例化
- 如何在数组中访问对象内的字符串
- 在C 中运行时从指针访问对象实例
- 有关使用矢量迭代器访问对象方法的问题
- 当对象的指针存储在矢量中时,如何访问对象中的方法?
- 显式调用"运算符 new"后无法访问对象的函数
- 尝试访问对象数组中的对象,但只保存了一个对象