Return the current object (*this) in C++?
I have the following code:
Code 1
class Student {
     int no;
     char grade[M+1];
 public:
     Student() {
         no = 0;
         grade[0] = '\0';
     }
     void set(int n, const char* g) {
         no = n;
         strcpy(grade, g);
     }
     const Student getObject() {
         return *this;
     }
     void display() const {
         cout << no << ", " << grade << endl;
     }
 };
Code 2:
// no change from code 1
const Student& getObject() {
         return *this;
     }
// no change from code 1
As the book I am reading explains the difference in the getObject() of the code 1 and 2 is that the getObject() of code 2 returns a reference to the current object, instead of a copy (for efficiency reasons).
However, I have tested (code 2) as follows:
Tested code:
Student harry, harry1;
    harry.set(123, "ABCD");
    harry1 = harry.getObject();
    harry1.set(1111,"MMMMMM");
    harry.display(); // Line 1 => displayed: 123, ABCD
    harry1.display(); / Line 2 => displayed: 1111, MMMMMM
I dont get it. If the getObject() returns a reference, then Line 1 in the tested code should开发者_如何学编程 also display 111, MMMMMM? Because I thought that harry1 should contain the address of harry object??? Or am I misunderstanding something?
Although harry.getObject() is a reference to the original object, you then ruin it with the assignment:
harry1 = harry.getObject();
which performs a copy.
Instead:
Student const& harry1 = harry.getObject();
You are assigning the reference returned by getObject to a Student, so it gets copied just a few steps later as in Code 1 (where it would be copied directly upon returning from getObject). Use 
Student& harry1 = harry.GetObject();
to obtain a reference to harry. Note that you must declare and initialize references in one step.
You are using actual objects, not pointers or references. When you say:
harry1 = harry.getObject()
the contents of harry are copied by the default assignment operator into harry1.
harry1 in your test code is an instance of Student, not a reference. Change it to this:
Student harry;
harry.set(123, "ABCD");
Student& harry1 = harry.getObject();
harry1.set(1111,"MMMMMM");
harry.display(); // Line 1 => displayed: 123, ABCD
harry1.display(); / Line 2 => displayed: 1111, MMMMMM
Common advise : define a copy constructor, private and not implemented:
private:
  Student(Student& xOther);
This way, if you happen to have unwanted copy, compiler will detect them (your harry1 is actually a copy). And if you expect to have copies, you can properly control how they are done, thus avoiding to mess with potential pointers or encapsulated objects.
 加载中,请稍侯......
      
精彩评论