I recently learned C ++ and used the copy constructor to raise some questions.
1 Class Test { 2 Private : 3 Int A; 4 Public : 5 Test (); 6 Test ( Const Test &T ){ 7 A = T.; 8 }; 9 ~ Test (); 10 Int Getdate (); // Returns the value of A, so I will not write it. 11 }
In this way, the value of member variable A of t can be directly assigned to a of this class. This shows that the scope of private is relative to the class, rather than the class of an object. As long as it is in a class with the same name, private variables can be directly called.
Then I changed it.
1 Class Test { 2 Private : 3 Int A; 4 Public : 5 Test (); 6 Test ( Const Test & T ){ 7 A = T. getdata (); 8 }; 9 ~ Test (); 10 Int Getdate (); // Returns the value of A, so I will not write it. 11 }
The compiler reports an error. The reason is that when the const object calls its own function, it will automatically convert the function to the const this pointer, that is to say, it will change the function to the const type, and the getdata in the class is not the const type, therefore, an error is reported.
The modification method is int getdata () const;