在运算符重载函数中使用运算符重载器
Use an operator overloader in an operator overloading function
我有以下类(在C++中):
class Card
{
public:
//other functions
std::ostream& operator<< (std::ostream& os)
{
if (rank < 11) os << rank;
else if (rank == 11) os << "J";
else if (rank == 12) os << "Q";
else if (rank == 13) os << "K";
else os << "A";
switch (suit)
{
case 0:
os << char (6);
break;
case 1:
os << char (3);
break;
case 2:
os << char (4);
break;
case 3:
os << char (5);
break;
}
}
private:
Suit suit;
Rank rank; //these are both pre-defined enums
}
这个类别:
class Hand
{
public:
std::ostream& operator<< (std::ostream& os)
{
for (std::vector<Card>::iterator iter = cards.begin(); iter < cards.end(); ++iter)
os << *iter << ", "; //THIS LINE PRODUCES THE ERROR
return os;
}
private:
std::vector<Card> cards;
};
但是,它会在标记的线上产生错误。假设它与Card
类中的<<
重载有关。我做错了什么?我该如何解决这个问题?
不能将插入作为成员函数重载到ostream
中,因为第一个参数是ostream
。你需要让它成为一个免费的功能:
std::ostream& operator<<(std::ostream&, Card const &);
您过载的操作员必须被称为:
Card c;
c << std::cout;
这是非常独特的。
public:
Suit suit;
Rank rank; //these are both pre-defined enums
使用此代码。。。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板