如何将类对象分配给指针?

时间:2013-03-14 23:35:29

标签: c++ pointers

如何使指针指向同一类的真实对象的内存位置?

Class A
{
    int num = 0;
    A(int n) {
        this->num = n;
    }
}

int main()
{
    A a(10);
    A * aPtr;

    // How do I make "aPtr" point at "a"?

    // something like
    // aPtr = a; (I know this wont work but what instead)
}

2 个答案:

答案 0 :(得分:1)

  

如何将“aPtr”指向“a”?

使用&(地址)运算符:

aPtr = &a;

答案 1 :(得分:1)

使用地址运营商:

A * aPtr = &a;                 // assume that & is not overloaded

#include <memory>

A * aPtr = std::addressof(a);  // more general