您的位置:首页 > 编程语言 > C语言/C++

C++Primer之友元

2016-01-11 11:18 239 查看
要想令某个成员函数作为友元,例如,在Wondow_mgr中的成员函数clear需要调用Screen类中的私有成员,则必须按照如下方式设计程序:

1.首先定义Window_mgr类,其中声明clear函数,但是不能定义它,在clear使用Screen的成员之前必须先声明Screen;

2.接下来定义Screen,包括对clear的友元声明;

3.最后定义clear,此时它才可以使用Screen的成员。

如下所示例子:

#include<iostream>
#include<string>

using std::cout;
using std::string;
using std::endl;

class Screen;

class Window_mgr{
public:
void clear(Screen &s);
};

class Screen{
friend void Window_mgr::clear(Screen &s);
private:
string contents;
public:
Screen(string s):contents(s){}
string getContents(){
return contents;
}
};

void Window_mgr::clear(Screen &s){
s.contents = "World";
}

int main(){
Screen s("Hello");
cout<<s.getContents()<<endl;
Window_mgr w;
w.clear(s);
cout<<s.getContents()<<endl;

return 0;
}


结果如下图所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++