0

I am learning design patterns. While studying the design pattern of Mediator, I try to compile below code in my laptop but get two "use of undefined type Chatroom" errors marked in the code. It seems that the compiler can not call Chatroom's member function even if I have pre-defined the class Chatroom. I want to have all the code in one cpp file. How can I do it?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Chatroom;

class PersonChat {
public:
    string name;
    Chatroom* room = NULL;
    vector<string> chat_log;

    PersonChat(const string& name) :
        name(name) {}

    void receive(const string& origin, const string& message) {
        string s{ origin + ":\"" + message + "\"" };
        cout << "[" + name + "\'s chat session] " + s + "\n";
        chat_log.emplace_back(s);
    }
    void say(const string& message) const {
//"use of undefined type Chatroom"
        room->broadcast(name, message);
    }
    void pm(const string& who, const string& message) const {
//"use of undefined type Chatroom"
        room->message(name, who, message);
    }
};

class Chatroom {
public:
    std::vector<PersonChat*> people;

    void join(PersonChat* p) {
        if (p != NULL) {
            string join_msg = p->name + " joins the chat.\n";
            people.push_back(p);
            p->room = this;
            broadcast("room", join_msg);
        }
    }
    void broadcast(const string& origin, const string& message) {
        for (auto& p : people) {
            if (p->name != origin) {
                p->receive(origin, message);
            }
        }
    }

    void message(const string& origin, const string& who, const string& message) {
        auto target = find_if(begin(people), end(people),
            [&](const PersonChat* p) {return p->name == who; });

        if (target != end(people)) {
            (*target)->receive(origin, message);
        }
    }
};









int main() {
    Chatroom room;
    PersonChat john{ "john" };
    PersonChat jane{ "jane" };
    PersonChat jack{ "jack" };
    room.join(&john);
    room.join(&jane);
    room.join(&jack);

    john.say("hi room");
    jane.say("jacky");


    return 0;
}
ppzzyy
  • 11

0 Answers0