矢量的内容不会打印

时间:2017-09-15 05:41:58

标签: c++ vector

所以我试图打印一个简单向量的内容,但是我遇到了一个奇怪的错误。这是代码:

srand(time(NULL));

for (int i = 0; i < 7; i++){
    AIhand[i] = deck[rand() % deck.size()];
    cout << AIhand[i] << endl;
}

'deck'是Card类的向量(它用于纸牌游戏)。 错误来自第一个'&lt;&lt;&lt;在cout线。 Visual Studio说“无运算符”&lt;&lt;“匹配这些操作数 - 操作数类型是:std :: ostream&lt;&lt; Card”。我将此问题作为一个新问题发布,因为我已添加<string><iostream>using namespace std;,这些是人们无法打印矢量问题的常用解决方案。

据我所知,我的语法是对的,但我对C ++比较陌生,所以它可能只是用户错误。

提前致谢!

编辑:这是Card类头文件:

#ifndef CARD_H_
#define CARD_H_

#include <string>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;

class Card {
public:
    Card(string newSuit, int newValue);
    string showCard();

private:
    int cardValue;
    string cardSuit;
};


#endif CARD_H_

这是Card .cpp文件:

#include "Card.h"
#include <sstream>
#include <iostream>
#include <ostream>

Card::Card(string newSuit, int newValue) {

    cardValue = newValue;

    cardSuit = newSuit;

}

string Card::showCard(){

    stringstream card;

    card << cardValue << " of " << cardSuit << endl;

    return card.str();
}

这是甲板

vector<Card> deck;

    for (int i = 0; i < 56; i++){
        for (int j = 0; j < 14; j++) {
            Card cuccos("Cuccos", j);
            deck.push_back(cuccos);
        }
        for (int j = 0; j < 14; j++){
            Card loftwings("Loftwings", j);
            deck.push_back(loftwings);
        }
        for (int j = 0; j < 14; j++){
            Card bullbos("Bullbos", j);
            deck.push_back(bullbos);
        }
        for (int j = 0; j < 14; j++){
            Card skulltulas("Skulltulas", j);
            deck.push_back(skulltulas);
        }

    }

1 个答案:

答案 0 :(得分:1)

由于你相对较新的C ++ ,我认为评论中存在误解

  

我在Cardhand类中定义了AIhand向量使用的ostream和iostream   [...]但它似乎没有什么区别

其他人询问的是,您是否为operator <<类定义了自定义ostream Card。您的回答是,您已添加了ostreamiostream标题。

简单的解决方案:尝试打印文本而不是Card类:

cout << AIhand[i].showCard() << endl;

更复杂的解决方案:告诉自己如何为卡片类重载operator <<

有关详细信息,请参阅相关问题:

Print function for class c++

How to properly overload the << operator for an ostream?