In: Computer Science
This class models people moving in together in real life using pointers in C++.
What test(s) could be added with the code below? At the end of this task, add them! (Answer this.)
class Person { public: Person(const string& name) : name(name) {} void movesInWith(Person& newRoomate) { roomie = &newRoomate; // now I have a new roomie newRoomate.roomie = this; // and now they do too } const string& getName() const { return name; } // Don't need to use getName() below, just there for you to use in debugging. const string& getRoomiesName() const { return roomie->getName(); } private: Person* roomie; string name; }; // write code to model two people in this world Person joeBob("Joe Bob"), billyJane("Billy Jane"); // now model these two becoming roommates joeBob.movesInWith(billyJane); // did this work out? (Answer this and explain why.) cout << joeBob.getName() << " lives with " << joeBob.getRoomiesName() << endl; cout << billyJane.getName() << " lives with " << billyJane.getRoomiesName() << endl;
What changes can be made to the Person class above to keep the methods "safe"? For example, the movesInWith method.
I dont understand what this above question means, please help!
#include <iostream> using namespace std; class Person { public: Person(const string& name) : name(name) { } void movesInWith(Person& newRoomate) { // If the passed person is not me.. // Because i can not be roomie of myself. if(&newRoomate != this) { roomie = &newRoomate; // now I have a new roomie newRoomate.roomie = this; // and now they do too } } const string& getName() const { return name; } // Don't need to use getName() below, just there for you to use in debugging. const string& getRoomiesName() const { return roomie->getName(); } private: Person* roomie; string name; }; int main() { // write code to model two people in this world Person joeBob("Joe Bob"), billyJane("Billy Jane"); // now model these two becoming roommates joeBob.movesInWith(billyJane); // did this work out? (Answer this and explain why.) cout << joeBob.getName() << " lives with " << joeBob.getRoomiesName() << endl; cout << billyJane.getName() << " lives with " << billyJane.getRoomiesName() << endl; }
************************************************** Added more safety in the case, where the same person is asked to be made roomie of itself. Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.