类的成员函数作为另一个类的友元
Member function of a class as friend to another class
在这段代码中,我将类B的max函数设置为类a的朋友,我还对类B进行了前向声明,但是它给出了错误
#include<iostream>
using namespace std;
class B;
class A
{
int a;
public:
void get()
{
cin>>a;
}
friend void B :: max(A , B);
};
class B
{
int b;
public:
void get()
{
cin>>b;
}
void max(A x, B y)
{
if (x.a > y.b)
cout<< " x is greater";
else cout<<"y is greater";
}
};
int main()
{
A x;
B y,c;
x.get();
y.get();
c.max(x,y);
}
B
在声明B::max
为友元方法时是不完整的。因此,编译器不知道是否存在这样的方法。
这意味着您需要
- 重新排序类,使
A
知道B
有方法B::max
和 - 在类定义之外实现方法
B::max
,当两个类都完成时,因为您访问内部变量。
通过const引用传递参数也是一个好主意。使用const
来强调您没有修改它们。通过引用传递以避免不必要的复制。
因此,考虑到这一点:
class A;
class B{
int b;
public:
void get(){
cin>>b;
}
void max(const A& x, const B& y);
};
class A{
int a;
public:
void get(){
cin>>a;
}
friend void B :: max(const A& , const B&);
};
void B::max(const A& x, const B& y) {
if (x.a > y.b)
cout<< " x is greater";
else
cout<<"y is greater";
}
As R Sahu已经回答:
不能使用:
friend void B :: max(A , B);
没有b的完整定义的这是你实现目标的方法:
#include<iostream>
using namespace std;
class A;
class B{
int b = 2;
public:
void max(A x, B y);
};
class A{
int a = 1;
public:
friend void B :: max(A , B);
};
void B::max(A x, B y){
if (x.a > y.b)
cout<< " x is greater";
else
cout<<"y is greater";
}
int main(){
A x;
B y,c;
c.max(x,y);
}
不能使用:
friend void B :: max(A , B);
没有B
的完整定义。
您需要重新考虑您的策略,以便您可以在不使用friend
声明或将B
的定义移动到A
定义之前的情况下实现该功能。
相关文章:
- 友元函数需要一个帮助程序函数
- 将四元数旋转的游戏对象旋转另一个四元数时出现问题
- C++:成员不可访问-使用友元函数允许一个类修改另一个类的成员数据
- 如何将一个类的成员函数用作另一类的友元函数
- 为什么T是未定义的?我正在尝试实现一个用于双链表的节点类,它不喜欢我使用友元运算符后的T
- 声明一个模板函数,将模板类友元的两个对象(仅)带到这两个专用化
- 我可以有一个从外部不可见但未在标头中定义的静态友元函数吗?
- 使用对另一个元组不同类型的元素的非常量引用来初始化元组的元素
- 成员函数与友元函数:为什么是一个而不是另一个?
- 另一个命名空间和 CRTP 中的模板友元函数
- c++存储映射元组的引用,以便在另一个函数中使用
- 如何在不使用友元类的情况下通过另一个类访问一个类的私有成员
- 如何通过友元函数将一个对象(类型a)传递给另一个对象(类型b)的私有对象(类型a)
- 如何将此对象传递给另一个对象并使用友元类 (c++) 访问其变量
- 为什么 PRIVATE 成员函数不能是另一个类的友元函数?
- 友元函数没有访问另一个友元类的私有成员
- 类的成员函数作为另一个类的友元
- 另一个类的友元类函数
- 有没有办法防止在不使用友元类 (C++) 的情况下从另一个类使用公共函数
- 使用友元函数访问一个类在另一个类中的数据