尝试重载"<<"运算符时,没有运算符"<<"匹配这些操作数错误



我是c++的新手,我正试图简单地从main.cpp文件中的Deck类中打印出一个向量向量。我想我需要使<lt;运算符,因为我试图输出的是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<lt;main.cpp中的卡片。不确定为什么Deck类中的重载运算符功能不能正常工作

此运算符的定义<lt;

friend std::ostream& operator<<(std::ostream& stream,  std::vector<std::vector<std::string>>& allCards) {
stream << allCards;
return stream;

}

没有道理。它是递归地调用自己。也就是说,运算符没有定义std::vector<std::vector<std::string>>类型的对象应该如何输出。

此外,将运算符声明为类Deck的友元函数也是没有意义的。

此外,编译器在语句中看不到运算符

std::cout << cards;

因为ADL(自变量相关查找(在这种情况下不起作用。

您需要在类Deck之外声明运算符。例如,您可以使用基于范围的for循环。例如

std::ostream & operator<<( std::ostream &stream, 
const std::vector<std::vector<std::string>> allCards ) 
{
for ( const auto &v : allCards )
{
for ( const auto &s : v )
{
stream << s << ' ';
}
stream << 'n';
}
return strean;
} 

您想要做的似乎是为Deck类型的对象重载操作符,比如

std::ostream & operator <<( std::ostream &stream, const Deck &deck );

最新更新