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

时间:2016-11-09 18:41:09

标签: c++ oop pointers

我创建了一个名为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方法中的问题如何返回指针(例如southnortheastwest

1 个答案:

答案 0 :(得分:2)

您是否真的在询问Room::getLinked()函数的正确定义语法是什么?

好的,你走了:

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