指向类的私有数据成员的指针

use*_*499 13 c++

是否可以声明指向类的私有数据成员的指针?如果是这样,你怎么做?

Tyl*_*nry 22

是的,和创建任何其他指针的方式相同.美中不足的是,当然,由于成员是私有的,你只能创建指针的类,在这里你可以看到成员.

class A 
{
  public:
    int* getFooPtr()
    {
       return &foo;  // OK; Inside the class foo is visible
    }

  private:
    int foo;
};

int main()
{
   A a;

   int* p_foo1 = &a.foo; // Illegal; Outside the class, foo is private
   int* p_foo2 = a.getFooPtr(); // OK; getFooPtr() is a public member function
}
Run Code Online (Sandbox Code Playgroud)

因此,可以创建指向私有成员的指针,但只能在类的成员函数内部,并且可以从成员函数返回那些创建的指针.返回指向私人成员的指针是否是一个好主意完全是另一个问题(通常这不是一个好主意).


Gab*_*ton 5

如果您利用C ++允许您在显式实例化中传递私有成员的地址的事实,则可以在声明类之外访问任何非静态私有成员。但是,您将无法访问静态私有成员,因为您必须使用此技术使用指向成员的指针。

struct A
{
     A() : x("proof!") {}
private:
     char const* x;
};

template class stow_private<A_x,&A::x>;

int main()
{
        A a;

        // Use the stowed private member pointer
        std::cout << a.*stowed<A_x>::value << std::endl;
};
Run Code Online (Sandbox Code Playgroud)

您可以在stowed<>此处找到的实现和详细信息:http : //bloglitb.blogspot.hu/2010/07/access-to-private-members-thats-easy.htmlhttps://gist.github.com/dabrahams/ 1528856


Bri*_*ndy 3

是的,这是可能的。不过,您必须从类的上下文中或有权friend访问该类的人中返回指针(或引用)。这是因为变量本身是私有的,因此无法以其他方式访问。

class C
{
public:
    int* getXPointer()
    {
        return &x;
    }

    int& getXReference()
    {
        return x;
    }

private:
    int x;
};


int main(int argc, char* argv[])
{
    C c;
    int* p = c.getXPointer();
    int& r = c.getXReference();
    assert(p == &r);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)