打印出结构数组的元素

printing out elements of an array of structs

我似乎无法弄清楚我做错了什么...我正在编写一个程序来玩 quatro 游戏,这是一种类似于 tic tac tow 的棋盘游戏。在游戏中,他们有 16 个独特的棋子,每个棋子有四个 "traits"。 (高或矮,黑色或白色,空心或填充,方形或圆形)

我创建了一个结构 "pieces",其中 "traits" 是一个成员。我将特征称为 W 代表白色,T 代表高,H 或空心......

无论如何,我只是想创建一个数组来保存所有可用的片段,并将它们显示在一个单独的缩小程序中。但是我似乎无法打印出可用数组的元素。

我得到的错误是

错误:std:cout << available[0]'

中的 'operator <<' 不匹配

这是我现在正在尝试的...

#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <algorithm>

using namespace std;

struct Pieces{

string traits;

};

int main()
{
  Pieces p1;
p1.traits = "WSHR";

Pieces p2;
p2.traits = "BSHR";

Pieces p3;
p3.traits = "WTHR";

Pieces p4;
p4.traits = "BTHR";

Pieces available [4] = {p1.traits,p2.traits,p3.traits,p4.traits};

cout << available[0];


return 0;

}

我添加了一堆库,希望这是问题所在。当我取消引用可用数组 ( &available[0] ) 时,地址会打印出来,但我似乎无法弄清楚如何在数组的第一个插槽中打印值。

如有任何帮助,我们将不胜感激。

error: not match for 'operator <<' in std:cout << available[0]'

你必须定义一个std::ostream& operator(std::ostream&, const Pieces&)运算符才能直接打印出Pieces:

std::ostream& operator(std::ostream& os, const Pieces& pcs) {
    os << pcs.traits;
    return os;
}

或者,您可以直接从 struct Pieces 输出 traits 成员:

std::cout << available[0].traits;

因为数组 available 包含 Pieces 类型的对象,对于 cout << available[0] 您正试图将 Pieces 对象传递给 operator<< of std::cout.

但是 cout::operator<< 没有为类型 Pieces 重载,所以它不知道该怎么做。

要么重载 operator<<[1] 要么简单地输出该结构中的字符串:

cout << available[0].traits;

[1] 示例见 πάντα ῥεῖ 的回答。

你应该重载'<<'运算符(输出流运算符),或者输出'traits'成员。此外,您可以使用自定义构造函数使它们更容易初始化,甚至可以使用 std::vector 容器:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct Pieces{
    Pieces(){} // default c'tor
    Pieces(const string& t)
        : traits(t) {}

    string traits;

    friend ostream& operator<< (ostream& stream, const Pieces& p);
};

// overload the output stream operator for convenience
ostream& operator<< (ostream& stream, const Pieces& p)
{
    stream << p.traits;
    return stream;
}


int main()
{
    Pieces p1("WSHR");  // neater if you write a constructor overload that inits the contents
    Pieces p2("BSHR");
    Pieces p3("WTHR");
    Pieces p4("BTHR");

    Pieces available[4] = { p1, p2, p3, p4 };
    // Or you could init the elements directly in the array; 
    Pieces a2[1] = { Pieces("WSHR") };

    cout << available[0] << endl; 

    // This is my favorite way to declare and init the array
    vector<Pieces> avail = { Pieces("WSHR"), Pieces("BSHR"), Pieces("WTHR"), Pieces("BTHR") };
    cout << avail[0] << endl;
}