成员函数作为友元
成员函数作为友元,只能是一种顺序.因为我们必须明确指出该成员函数属于哪个类,只有类的声明而无定义,无法在友元声明中指出该成员函数所属的类.以window_mgr类的成员函数clear作为Screen类的友元为例.
必须先定义window_mgr类,而不能先定义Screen类(此时会对window_mgr作前向声明).
1 #include <iostream> 2 #include <string> 3 4 using std::string; 5 using std::cout; 6 using std::endl; 7 8 #if 0//正确的形式 9 class window_mgr { 10 public: 11 void clear(); 12 }; 13 14 class Screen { 15 friend void window_mgr::clear(); 16 private: 17 string contents; 18 public: 19 Screen() = default; 20 Screen(char c) : contents(10, c) {} 21 }; 22 23 void window_mgr::clear() 24 { 25 Screen myScreen('b'); 26 cout << "清理之前:" << endl; 27 cout << myScreen.contents << endl; 28 myScreen.contents = ""; 29 cout << "清理之后:" << endl; 30 cout << myScreen.contents << endl; 31 cout << "================================" << endl; 32 } 33 34 int main() 35 { 36 window_mgr w; 37 w.clear(); 38 return 0; 39 } 40 41 42 #else if //!!!测试 : 错误的方式. 43 class window_mgr; 44 //void window_mgr::clear(); 45 class Screen { 46 friend void window_mgr::clear();//只有声明而无定义:无法访问window_mgr的成员函数clear. 47 private: 48 string contents; 49 public: 50 Screen() = default; 51 Screen(char c) : contents(10, c) {} 52 }; 53 54 class window_mgr { 55 public: 56 void clear(); 57 }; 58 59 void window_mgr::clear() 60 { 61 Screen myScreen('b'); 62 cout << "清理之前:" << endl; 63 cout << myScreen.contents << endl; 64 myScreen.contents = ""; 65 cout << "清理之后:" << endl; 66 cout << myScreen.contents << endl; 67 cout << "================================" << endl; 68 } 69 70 int main() 71 { 72 window_mgr w; 73 w.clear(); 74 return 0; 75 } 76 #endif
启用42行后面的代码,编译器(VS2015)给出的错误提示如下:
从46行的错误提示可以看出,尽管只是用作友元声明,未定义的类(有前向声明)也无法访问其成员.
不是尽力而为,而是全力以赴.