可以通过其地址访问私有变量吗?

jma*_*erx 10 c++

公共函数是否可以返回指向类中私有变量的指针.如果是这样/如果没有,会发生什么?它会崩溃还是有什么高度不安全的?可以读取或写入指向的数据吗?谢谢

Jam*_*lis 23

是的,成员函数可以将指针(或引用)返回给私有数据成员.这没有什么不妥,除了在大多数情况下它破坏了封装.

当然可以通过返回的指针或引用来读取数据成员.是否可以写入取决于返回的指针或引用是否是const限定对象(即,如果返回a const T*,则无法修改指向的对象T).例如:

class Example
{
public:
    int*       get()             { return &i; }
    const int* get_const() const { return &i; }
private:
    int i;
};

int main()
{
    Example e;

    int* p = e.get();
    int a = *p;    // yes, we can read the data via the pointer
    *p = 42;       // yes, we can modify the data via the pointer

    const int* cp = e.get_const();
    int b = *cp;   // yes, we can read the data via the pointer
    *cp = 42;      // error:  pointer is to a const int         
}
Run Code Online (Sandbox Code Playgroud)

  • @jack london:IMO,在 C++ 中,如果你打算进行手动内存管理,你就不能在任意指针上调用“delete”并期望逃脱它。如果您手动管理内存,您必须知道自己在做什么。 (2认同)
  • @jack:它并不比 `int i; 更危险。删除 &i;`。 (2认同)