#include <iostream>
class A
{int a,b;
public:
A(int x,int y);
void display();
friend void show(A t);
};
A::A(int x,int y)
{a=x;b=y;}
void display()
{cout<<a<<endl;
}
void show(A t)
{
cout<<t.b<<endl;
}
void main()
{
A temp(1,2);
temp.display();
temp.show(temp);
cout<<temp.a<<endl;
}
下面是修改过的代码,可参考理解
#include <iostream>
using namespace std; //后面的cout需要用到
class A
{
int a,b; //默认是private属性
public:
A(int x,int y);
void display();
friend void show(A t);
};
A::A(int x,int y)
{
a=x;
b=y;
}
void A::display()
{
cout<<a<<endl;
}
void show(A t)
{
cout<<t.b<<endl;
}
int main()
{
A temp(1,2);
temp.display();
show(temp); //友元函数不属于类的成员,不能用 . 来调用
//cout<<temp.a<<endl; //C++默认是private属性的,不能直接调用
}