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

C++大学基础教程_10_4_friend函数和friend类

2014-07-14 22:51 531 查看
//testMain.cpp

#include <iostream>
using namespace std;

class Count
{
//使用非friend函数来修改private成员是错误尝试
//用friend函数修改类的private数据
friend void setX(Count &,int);
public:
Count()
:x(0)
{}//函数体为空

void print() const
{
cout << x << endl;
}
private:
int x;
};

void setX(Count &c,int val)
{
c.x = val;
}

int main()
{
Count counter;
cout << "counter.x after instantiation: " ;
counter.print();
setX(counter,8);
cout << "counter.x after call to setX friend function: ";
counter.print();
system("pause >> cout");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: