//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;
}
C++大学基础教程_10_4_friend函数和friend类
最新推荐文章于 2022-07-27 20:43:47 发布