2015-04-28 36 views
-4

我正在研究访问私人班级成员。我想更好地了解这一点。'&'表示堆分配指针是什么意思?

class Sharp 
{ 
public: 
    Sharp(); 
    ~Sharp(); 
private: 
    DWORD dwSharp; 
public: 
    void SetSharp(DWORD sharp) { dwSharp = sharp; }; 
}; 

Sharp::Sharp() 
{ 
    dwSharp = 5; 
} 
Sharp::~Sharp() 
{ 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    DWORD a = 1; 
    *(DWORD*)&a = 3; 

    Sharp *pSharp = new Sharp; 
    cout << *(DWORD*)&pSharp[0] << endl; 

    cout << *(DWORD*)pSharp << endl; 
    cout << (DWORD*&)pSharp[0] << endl; 

    //pSharp = points to first object on class 
    //&pSharp = address where pointer is stored 
    //&pSharp[0] = same as pSharp 
    //I Would like you to correct me on these statements, thanks! 


    delete pSharp; 
    system("PAUSE"); 
    return 0; 
} 

所以我的问题是,什么是pSharp&pSharp&pSharp[0],也请解释cout << (DWORD*&)pSharp[0] << endl;,为什么它输出0000005

谢谢!

+0

虽然不是常规的,但我怀疑它几乎等同于'(DWORD *)&pSharp [0]',它是'pSharp'的第0个元素的地址作为指向'DWORD'的指针。 –

+0

'cout <<(DWORD *&)pSharp [0] << endl;' 这是获得存储在索引为'0'的数组中的值,并将其解释为指向DWORD的指针。这就是为什么结果是'5'。我猜你的意思是: 'cout <<(DWORD *)&pSharp [0] << endl;' –

回答

2

是什么pSharp

这是一个指向Sharp对象实例。

是什么& pSharp

这是运营商的地址(也没关系,这是一个指针)。

是什么& pSharp [0]

我不知道为什么它是这样写的,但它只是把地址和[0]刚刚从内存的开头开始由指针指向。

为什么它输出0000005

由于dwSharp类成员是在构造函数设置为5。