There is a class Room Room and there is a class Furniture Furniture class. How to aggregate these two classes by aggregation and then create a method in the class Room that would display the entire list of furniture?

class Room; class Furniture { string chair; string cupboard; string sofa; }; 

    2 answers 2

     #include <iostream> #include <string> using namespace std; class Furniture { public: string chair; string sofa; string cupboard; Furniture() { chair = ""; cupboard = ""; sofa = ""; } Furniture(string ch, string c, string s) { chair = ch; cupboard = c; sofa = s; } void Furniture::print() { cout << chair + " " + cupboard + " " + sofa << endl; } }; class Room { private: Furniture f; public: void printFurniture() { f.print(); } }; 

    I suppose that's what you meant.

    However, such an implementation looks very doubtful. True, it all depends on the task, but creating an abstract Furniture class and expanding it to Chair , Sofa , Cupboard would be much more convenient in my opinion.

     class Room { private: Chair ch; Sofa s; Cupboard c; }; 
    • THANK! I know, it is not allowed to write thanks, but thank you very much !!! - Maryna Said
    • With an abstract class then: class Room { private: std::vector<Furniture*> furniture; }; class Room { private: std::vector<Furniture*> furniture; }; - Fat-Zer

    The state of the room should not depend on the amount of furniture in it, so the room should not consist of furniture, but let it consist of windows and doors, walls and ceilings ... Therefore, let it have Furniture * pf, and when I want to remove it from the room furniture, it will be easy, i.e. pf = 0. There is no furniture, but there is a room ...

     using std::string; class Furniture { string chair, sofa, cupboard; // ... }; class Room { Furniture* pf; //... public: Room(Furniture* havings = 0) : pf(havings) {} //... ~Roome() { delete pf; } Roome& remove furniture() { if(pf) pf = 0; return *this; } // убрать Roome& add_furniture() { ...... } // добавить void show_furniture() const { std::cout << pf->chair <<'\n' <<pf->sofa <<'\n' << pf->cupboard <<'\n';} }; 

    and when you destroy a room, the furniture in it will be destroyed ...

    • And why do you put a pointer near the Furniture in the class Room? - Maryna Said
    • I have already explained. When I want to have no furniture in the room or add furniture, I can do it in the room methods. Now add for clarity - AR Hovsepyan
    • read carefully not only the code, but also the comment - I think you will understand, if not, sorry - I do not have the practice of overcoming ... - AR Hovsepyan