如何从函数返回类成员的指针

How to return a pointer of a class member from a function

本文关键字:成员 指针 返回 函数      更新时间:2023-10-16

我创建了一个名为Room的类,如下所示

#ifndef ROOM_H
#define ROOM_H
#include <string>
class Room
{
private:
    std::string name;
    std::string description;
    Room* south;
    Room* north;
    Room* east;
    Room* west;
public:
    //CONSTRUCTOR
    Room();
    Room(std::string name, std::string desc);
    //METHODS
    std::string getName();
    std::string getDescription();
    void link(Room *r, std::string direction);
    Room *getLinked(std::string direction);
    void printLinked();
    ~Room();

};
#endif // ROOM_H

/*************************************************************************/

void Room::link(Room *r, std::string direction)
{
    if (direction == "south")//THIS IS JUST FOR TEST
    {
        this->south = this->getName();
    }
}
/*************************************************/
Room Room::*getLinked(std::string direction)
{
    return south;
}

这是我在getLinked方法中的问题,我如何返回指针(例如south, north, east, west)

您实际上是在问Room::getLinked()函数的正确定义语法是什么?

好吧,给你:

Room* Room::getLinked(std::string direction) {
    if(direction == "south") {
        return south;
    }
    // ... the other directions
    return nullptr;
}