拷贝构造函数和赋值运算符函数为什么可以访问传给它的引用对象的私有成员?

代码如下: 
 1 class String
 2 {
 3 public:
 4       String(const char *str=NULL);
 5       String(const String &other);
 6       ~String(void);
 7       String &operator = (const String &other);
 8 private:
 9        char *m_data;
10 };
11 
12 String &String::operator = (const String &other)
13 {
14     if(this == &other)//自己拷贝自己就不用拷贝了
15         return *this;
16     delete m_data;//删除被赋值对象中指针变量指向的前一个内存空间,避免内存泄漏
17     int length = strlen(other.m_data);//计算长度
18     m_data = new char[length+1];//申请空间
19     strcpy(m_data, other.m_data);//拷贝
20     return *this;
21 }        

m_data不是String类的私有成员吗?
为什么可以直接other.m_data?不是只有公共成员才可以吗?

同类对象互为友元!

 1 #include <iostream> 
 2 using namespace std; 
 3 
 4 class foo
 5 {
 6 public:
 7     foo(int na=0) : a(na) {}
 8 
 9     void func(foo& f)
10     {
11         f.a = 1;
12     }
13 
14     void print_foo()
15     {
16         cout << a << endl;
17     }
18 private:
19     int a;
20 };
21 
22 int main(){ 
23     foo f1;
24     foo f2;
25     f1.func(f2);
26     f1.print_foo();
27     f2.print_foo();
28 
29     system("pause"); 
30     return 0; 
31 } 

输出:

       0

       1

说明:不仅仅是拷贝构造函数和赋值运算符函数可以访问传给它的引用对象的私有成员,其它类成员函数也可以访问传给它的引用对象的私有成员。因为,同类对象互为友元!

原文地址:https://www.cnblogs.com/xiaoxu1st/p/3850896.html