最近遇到这样一个面试题:面试题 CString函数拷贝控制成员的编写
过程中遇到一个问题,真是当时让我疑惑不解:查查资料,原来是一时糊涂,看看人家的解答:不错,遂转一下(很简单,就是当时没转过弯来)
原文如下:
http://blog.csdn.net/randyjiawenjie/article/details/6667146
这个题目很奇怪啊,今天下午在看拷贝构造函数的时候,突然看到了很奇怪的一句话:
[cpp] view plain copy
1. class CExample
2. {
3. public:
4. CExample(){pBuffer=NULL; nSize=0;}
5. ~CExample(){delete pBuffer;}
6. CExample(const CExample&);
7. void Init(int n){ pBuffer=new char[n]; nSize=n;}
8. private:
9. char *pBuffer;
10. int nSize;
11. };
12. CExample::CExample(const CExample& RightSides)
13. {
14. nSize=RightSides.nSize; //!!!!!!请注意这句话!!!!!!
15. pBuffer=new char[nSize];
16. memcpy(pBuffer,RightSides.pBuffer,nSize*sizeof(char));
17. }
感叹号部分我很奇怪,不是不允许对象许访问私有变量成员么?怎么回事,而且还能编译通过。
1.为什么对象a可以直接访问私有的x(a.x)成员见http://topic.csdn.net/u/20110504/22/738aede9-3909-4d74-82fd-8d4a2f2f12a5.html
给出了一个解答:因为A(const A&a)是他的成员函数。
在我的例子也是如此:CExample::CExample(const CExample& RightSides)是CExample的成员函数,所以可以访问同类型对象的私有成员。即RighSides.nSize的调用可以编译用过,但是,你在main函数里面直接写上:
[cpp] view plain copy
1. int main(int argc, char* argv[])
2. {
3. CExample theObjone;
4. theObjone.nSize;
5. return 0;
6. }
编译器肯定是报错,提示你nSize是私有变量,不允许对象进行访问。
随后,我又做了一个实验:
[cpp] view plain copy
1. #include <iostream>
2.
3. using namespace std;
4. class T{
5. private:
6. int m_data;
7. };
8. class CTest
9. {
10. public:
11. CTest(); //构造函数
12. CTest(const CTest &); //复制构造函数
13. CTest & operator = (const CTest &); //赋值符
14. void print(){
15. cout << m_data << endl;
16. };
17. int print1(const CTest &);
18. int print2(const T&);
19. private:
20. int m_data;
21. };
22.
23. CTest::CTest()
24. {
25. cout<<"Constructor of CTest"<<endl;
26. }
27.
28. CTest::CTest(const CTest& arg)
29. {
30. cout << arg.m_data <<endl;
31. cout<<"Copy Constructor of CTest"<<endl;
32. }
33.
34. CTest & CTest::operator = (const CTest & arg)
35. {
36. cout<<"Assign function of CTest"<<endl;
37. }
38. int CTest :: print1(const CTest & arg){
39. cout << arg.m_data <<endl;
40. return 0;
41. }
42. int CTest::print2(const T& arg){
43. cout << arg.m_data << endl;
44. }
45. int main()
46. {
47. CTest a;
48. return 0;
49. }
请注意print()、print1()、print2()的区别;
print()自然不用说,成员函数访问类的私有变量,编译通过;
print1():print1是CTest类的成员函数,而print1的形参是const CTest&arg,arg的类型就是CTest,根据成员函数可以访问私有变量,故编译通过
print2():print2是CTest类的成员函数,但是print2的形参类型是T,不是CTest,print2不是T的成员函数,不能访问类的私有变量,故编译不能通过