classcexample{ Public: Cexample () {pbuffer=null; Nsize=0;} ~cexample () {Deletepbuffer;} Cexample (Constcexample&); voidInit (intN) {pbuffer=New Char[n]; Nsize=N;}Private: Char*pbuffer; intnSize;}; Cexample::cexample (Constcexample&rightsides) {NSize=rightsides.nsize;//!!!!!! Please pay attention to this sentence!!!!!! Pbuffer=New Char[NSize]; memcpy (Pbuffer,rightsides.pbuffer,nsize*sizeof(Char));}
Exclamation point I'm surprised that I'm not allowed to access private variable members? What's going on, and it's going to compile and pass.
1. Why object A can directly access the private X (a.x) members see http://topic.csdn.net/u/20110504/22/738aede9-3909-4d74-82fd-8d4a2f2f12a5.html
Gives a solution: because a (const A&A) is his member function.
The same is true in my example: cexample::cexample (const cexample& rightsides) is a member function of cexample, so it is possible to access private members of the same type object. That is, the righsides.nsize call can be compiled, but you write it directly inside the main function:
int Main (intChar* argv[]) {cexample theobjone;theobjone.nsize; return 0 ;}
The compiler is definitely an error, prompting you to nsize is a private variable that does not allow access to the object.
Then I did another experiment:
#include <iostream>using namespacestd;classt{Private: intm_data;};classctest{ Public: CTest (); //constructor FunctionCTest (ConstCTest &);//copy ConstructorCTest &operator= (ConstCTest &);//Assignment Character voidprint () {cout<< m_data <<Endl;};intPrint1 (ConstCTest &);intPrint2 (Constt&);Private: intm_data;}; Ctest::ctest () {cout<<"Constructor of CTest"<<Endl;} Ctest::ctest (Constctest&Arg) {cout<< Arg.m_data <<Endl; cout<<"Copy Constructor of CTest"<<Endl;} CTest& CTest::operator= (ConstCTest &Arg) {cout<<"Assign function of CTest"<<Endl;}intCTest:: Print1 (ConstCTest &Arg) {cout<< Arg.m_data <<Endl; return 0;}intCTest::p Rint2 (Constt&Arg) {cout<< Arg.m_data <<Endl;}intMain () {CTest A;return 0;}
Please note the difference between print (), Print1 (), Print2 ();
Print () Naturally needless to say, member functions access the class's private variables, compiled through;
Print1 ():p rint1 is a member function of the CTest class, and the PRINT1 parameter is the const ctest& arg,arg type is ctest, the private variable can be accessed according to the member function, so the compiler passes
Print2 ():p Rint2 is a member function of the CTest class, but the Print2 parameter type is T, not ctest,print2 is not a member function of T, cannot access the private variable of the class, so compilation cannot pass
Transferred from: http://blog.csdn.net/randyjiawenjie/article/details/6667146
An understanding of a problem with C + + (private variable member)