C++ C+中的成员函数作为友元函数+;
我在运行以下使用friend函数的代码时出错。我的类XYZ1有一个friend函数,它是ABC1类的成员函数(findMax)。我的类声明如下C++ C+中的成员函数作为友元函数+;,c++,member,friend,C++,Member,Friend,我在运行以下使用friend函数的代码时出错。我的类XYZ1有一个friend函数,它是ABC1类的成员函数(findMax)。我的类声明如下 class XYZ1; class ABC1 { int a; public : ABC1() { a =20; } void findMax(XYZ1 p) { if (p.x > a) cout<< "Max is "<<p.x;
class XYZ1;
class ABC1
{
int a;
public :
ABC1()
{
a =20;
}
void findMax(XYZ1 p)
{
if (p.x > a) cout<< "Max is "<<p.x;
else cout <<"Max is "<<a;
}
};
class XYZ1
{
int x;
public :
XYZ1()
{
x =10;
}
friend void ABC1::findMax(XYZ1);
};
main()
{
XYZ1 p;
ABC1 q;
q.findMax(p);
}
XYZ1类;
ABC1类
{
INTA;
公众:
ABC1()
{
a=20;
}
无效findMax(XYZ1 p)
{
如果(p.x>a)不能您必须拥有类XYZ1
的完整声明,以便编译器能够编译使用它的代码
因此,将void findMax(XYZ1 p)
的实现移动到类XYZ1的声明下方:
class ABC1
{
...
void findMax(XYZ1 p);
};
class XYZ1
{
...
friend void ABC1::findMax(XYZ1 p);
};
void ABC1::findMax(XYZ1 p)
{
...
}
在定义类XYZ1之后定义findMax方法
#include <iostream>
using namespace std;
class XYZ1;
class ABC1
{
int a;
public :
ABC1()
{
a =20;
}
void findMax(XYZ1 p);
};
class XYZ1
{
int x;
public :
XYZ1()
{
x =10;
}
friend void ABC1::findMax(XYZ1);
};
void ABC1::findMax(XYZ1 p)
{
if (p.x > a) cout<< "Max is "<<p.x;
else cout <<"Max is "<<a;
}
int main()
{
XYZ1 p;
ABC1 q;
q.findMax(p);
return 0;
}
#包括
使用名称空间std;
XYZ1类;
ABC1类
{
INTA;
公众:
ABC1()
{
a=20;
}
void findMax(XYZ1 p);
};
XYZ1类
{
int x;
公众:
XYZ1()
{
x=10;
}
friend void ABC1::findMax(XYZ1);
};
void ABC1::findMax(XYZ1 p)
{
如果(p.x>a)可以,那么main
的返回类型是什么?