简体   繁体   中英

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

I have created class called Room as follows

#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;
}

And here is my question in getLinked method how can I return the pointer (eg south , north , east , west )

Are you actually asking what's the correct definition syntax for the Room::getLinked() function is?

Well, here you go:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM