没有运算符“<<”尝试重载“<<”时,匹配这些操作数会出错。操作员
我是 C++ 新手,我试图简单地从 main.cpp 文件中的 Deck 类中打印出向量的向量。我想我需要超载 <<运算符,因为我试图输出的是 Deck 对象的成员变量之一,但我在实现它时遇到了麻烦。如果这很重要的话,我还试图使套牌成为单身人士。
这是 Deck.h:
#define Deck _h
#include <vector>
#include <iostream>
class Deck {
public:
static Deck& Get() {
return deck_instance;
}
std::vector<std::vector<std::string>> getAllCards() {
return allCards;
}
friend std::ostream& operator<<(std::ostream& stream, std::vector<std::vector<std::string>>& allCards) {
stream << allCards;
return stream;
}
private:
Deck() {}
static Deck deck_instance;
std::vector<std::vector<std::string>> allCards = { {
// All clubs
"assets/2_of_clubs.png",
"assets/3_of_clubs.png",
"assets/4_of_clubs.png",
"assets/5_of_clubs.png",
"assets/6_of_clubs.png",
"assets/7_of_clubs.png",
"assets/8_of_clubs.png",
"assets/9_of_clubs.png",
"assets/10_of_clubs.png",
"assets/jack_of_clubs.png",
"assets/queen_of_clubs.png",
"assets/king_of_clubs.png",
"assets/ace_of_clubs.png"},
// All diamonds
{"assets/2_of_diamonds.png",
"assets/3_of_diamonds.png",
"assets/4_of_diamonds.png",
"assets/5_of_diamonds.png",
"assets/6_of_diamonds.png",
"assets/7_of_diamonds.png",
"assets/8_of_diamonds.png",
"assets/9_of_diamonds.png",
"assets/10_of_diamonds.png",
"assets/jack_of_diamonds.png",
"assets/queen_of_diamonds.png",
"assets/king_of_diamonds.png",
"assets/ace_of_diamonds.png"},
};
#endif
这是 main.cpp:
#include "Deck.h"
#pragma warning(pop)
#undef main
int main(int argc, char* args[]) {
Deck deck = Deck::Get();
std::vector<std::vector<std::string>> cards = deck.getAllCards();
std::cout << cards;
return 0;
}
错误是当我尝试 cout << main.cpp 中的卡片。不确定为什么 Deck 类中的重载运算符函数不起作用
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
运算符的这个定义 <<
没有意义。它递归地调用自身。也就是说,该运算符未定义应如何输出
std::vector>
类型的对象。此外,将运算符声明为类
Deck
的友元函数也是没有意义的。此外,编译器在该语句中看不到运算符,
因为 ADL(参数相关查找)在这种情况下不起作用。
您需要在
Deck
类外部声明该运算符。例如,您可以使用基于范围的 for 循环。例如,您似乎想要做的是重载
Deck
类型的对象的运算符,例如This definition of the operator <<
does not make a sense. It is recursively calls itself. That is the operator does not define how an object of the type
std::vector<std::vector<std::string>>
should be outputted.Also there is no sense to declare the operator as a friend function of the class
Deck
.Moreover the compiler does not see the operator in this statement
because ADL (argument-dependent lookup) does not work in this case.
You need to declare the operator outside the class
Deck
. You could for example use a range-based for loop. For exampleIt seems what you are trying to do is to overload the operator for objects of the type
Deck
something like