成员函数在C++中用作友元函数
Member functions as Friend functions in C++
我在运行以下代码以使用友元函数时收到错误。我的类XYZ1有一个友元函数,它是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;
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);
}
错误:friend3.cpp:14:7: 错误:"p"的类型不完整friend3.cpp:4:7:错误:"结构 XYZ1"的前向声明
请帮忙
在定义类 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;
}
您必须具有完整的class XYZ1
声明,编译器才能编译使用它的代码。
因此,将void findMax(XYZ1 p)
的实现移至class XYZ1
声明下方:
class ABC1
{
...
void findMax(XYZ1 p);
};
class XYZ1
{
...
friend void ABC1::findMax(XYZ1 p);
};
void ABC1::findMax(XYZ1 p)
{
...
}
相关文章:
- C++模板来检查友元函数的存在
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 模板类中的模板友元函数
- C++ 17 个友元函数声明和内联命名空间
- 将派生类的构造函数声明为父类的友元
- 友元函数需要一个帮助程序函数
- 在基/派生类的成员函数/友元函数中派生* 到 Base* 的转换
- 模板类的非模板函数友元