1 c++ constructor pointers object
我想知道如何在c ++的构造函数中创建一个指向新创建对象的指针?
课程的地址是什么?
class MyClass
{
public:
};
class MyClass2
{
public:
//I need a pointer to the created object
MyClass2 *pObjectName;
//Constructor
MyClass2()
{
pObjectName = &//I have no clue how to get the adress of the (not yet) created object.
}
};
int main()
{
//The way it works
//Makes Object
MyClass *pObject;
MyClass Object;
//pObject points to Object
pObject = &Object;
//Prints adress of Object
printf("%p", pObject);
//The way I would like to see it work
MyClass2 Object2;
//Prints adress of Object
printf("%p", Object2.pObjectName);
}
Run Code Online (Sandbox Code Playgroud)
这将是:
MyClass2()
{
pObjectName = this;
}
Run Code Online (Sandbox Code Playgroud)
但你不需要这样做.甲this指针隐式传递给一个类的每一个非静态成员函数.
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |