我定义了一个函数,它返回两个整数(属于 A 类)中的最大数。我如何让它适用于另一个 B 类?(作为它的友元函数?)
class A
{
int a;
int b;
public:
void setvalue(){
a=10;
b=20;
}
int max(){
if(a>b){
return a;
}
else{
return b;
}
}
};
class B
{
int c;
int d;
public:
void setvalue(){
c=10;
d=20;
}
friend int A::max();
};
int main()
{
A x;
x.setvalue();
cout<<"max is"<<x.max();
B y;
y.setvalue();
cout<<"max is"<<y.max();
return 0;
}
prog.cpp:38:20: error: 'class B' has no member named 'max'
cout<<"max is"<<y.max();`
最佳答案
这个
friend int A::max();
是友元成员函数的正确声明。
问题是B类没有成员函数max。所以这个表达式
y.max()
发出一个错误。
看来你需要的是在类B中继承类A,并将成员函数max声明为虚函数。
关于c++ - 如何将一个类的成员函数用作另一个类的友元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58670838/