如何在多个类中使用友元函数
How to use friend function in multiple classes
我正在尝试创建一个非成员operator<<
。但是,我希望两个类都可以访问该操作符。操作符是
void operator<< (ClassA & a, ClassB & b)
在两个类的公共部分,我说:
friend void operator<< (ClassA & a, ClassB & b);
然而,操作符可以访问CLass B
中的私有成员变量,而不能访问Class A
中的私有成员变量。
为什么?
实际代码:在cpp文件中:
void operator<< (Hand& h, Deck& d){
h.hand.push_back(d.card[0]);
sort(h.hand.begin(),h.hand.end());
d.card.erase(d.card.begin());
}
头文件:
class Deck {
private:
vector<Card> card;
public:
friend void operator<< (Hand& , Deck& );
};
class Hand {
private:
vector<Card> hand;
public:
friend void operator<< (Hand& , Deck& );
};
卡片文件不工作
将更新为编辑后的问题:以下代码对我来说编译没有问题:
#include <vector>
#include <algorithm>
typedef int Card;
class Hand; // NOTE forward declaration
class Deck {
private:
std::vector<Card> card;
public:
friend void operator<< (Hand& , Deck&);
};
class Hand {
private:
std::vector<Card> hand;
public:
friend void operator<< (Hand& , Deck&);
};
void operator<< (Hand& h, Deck& d) {
h.hand.push_back(d.card[0]);
std::sort(h.hand.begin(),h.hand.end());
d.card.erase(d.card.begin());
}
int main()
{
}
您是否忘记在头文件中转发声明Hand ?
您可能会感到困惑,因为可以在类的一个声明中定义静态友元函数的主体。然而,友元声明始终只是一个声明。因此,实际上
struct A;
struct B;
struct A
{
friend bool operator<<(A const&, B const&);
};
struct B
{
friend bool operator<<(A const&, B const&);
};
bool operator<<(A const&, B const&)
{
// access to both A and B
return false;
}
等价于
struct A;
struct B;
struct A
{
friend bool operator<<(A const&, B const&)
{
// access to both A and B
return false;
}
};
struct B
{
friend bool operator<<(A const&, B const&);
};
相关文章:
- C++模板来检查友元函数的存在
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 模板类中的模板友元函数
- C++ 17 个友元函数声明和内联命名空间
- 友元函数需要一个帮助程序函数
- 在类内定义的友元函数与类外定义的友元函数的查找规则之间的差异
- 运算符重载在 C++ 中使用友元函数
- 类C++友元函数无法访问封装的类
- 函数指针作为友元函数