我对这些 C++ 指针有点困惑,我想知道是否可以在构造函数中创建一个指向类实例的指针(如下所示)。
class Room{
public:
Room();
~Room();
private:
Room* ptrToSelf;
};
Room::Room(){
ptrToSelf = &(what should I write in here to have the pointer point to it)
}
我知道这听起来很疯狂(这里是新手),但我只是想知道这是否可行。有人可以给我解释一下吗?
非常感谢
编辑:
谢谢大家这么快回复我。我问是因为我想使用公共(public) Room*::getPointer();
方法返回类的指针。我有一个从一个房间移动到另一个房间的角色,我正在使用指针来实现这一点。我以字符串的形式从用户那里获取输入,但我无法将该字符串传递给我创建的 character.moveTo(const Room*)
方法的函数。我需要一种方法将字符串“转换”为类的指针,以便我可以将指针传递给方法。
编辑:
我正在考虑实现一种方法,该方法将根据字符串类型参数返回对象的指针:
Room::Room* getPointer(const string &nameOfRoom){
//I can't use this return statement as the following error
//Error: 'this' may only be used inside a nonstatic member function
return this;
编辑(希望是最后一个):
这会返回我正在寻找的东西吗?
Room::Room* getPointer(const string &nameOfRoom){
return &Room();
}
或者它正在返回一个新房间的地址?
谢谢
最佳答案
你不需要这样做,因为你的类将有一个隐式的 this 指针
this; // can be called anywhere in your class to access yourself
关于c++ - 在构造函数中创建一个指针以指向 C++ 中类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711455/