gpt4 book ai didi

c++ - 在构造函数 C++ 中创建指向对象的指针

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:27 25 4
gpt4 key购买 nike

我想知道如何在 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);

}

最佳答案

应该是:

MyClass2()
{
pObjectName = this;
}

但是您不需要那样做。 this 指针被隐式传递给类的每个非静态成员函数。

关于c++ - 在构造函数 C++ 中创建指向对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com