🛌

【C++】構造体を体よく表示したい

2025/02/11に公開

構造体を一度に標準出力へ

Pythonであれば、構造を持つデータであろうとも簡単に表示できます。

>>> list1 = ['1', '2']
>>> dict1 = {'name': '惣左衛門', 'age': 3}
>>> print(list1)
['1', '2']
>>> print(dict1)
{'name': '惣左衛門', 'age': 3}

しかしC++ではそうもいかないようで⋯

(引用:https://learn.microsoft.com/ja-jp/cpp/cpp/struct-cpp?view=msvc-170)

#include <iostream>
using namespace std;

struct PERSON {   // Declare PERSON struct type
    int age;   // Declare member types
    long ss;
    float weight;
    char name[25];
} family_member;   // Define object of type PERSON

struct CELL {   // Declare CELL bit field
    unsigned short character  : 8;  // 00000000 ????????
    unsigned short foreground : 3;  // 00000??? 00000000
    unsigned short intensity  : 1;  // 0000?000 00000000
    unsigned short background : 3;  // 0???0000 00000000
    unsigned short blink      : 1;  // ?0000000 00000000
} screen[25][80];       // Array of bit fields

int main() {
    struct PERSON sister;   // C style structure declaration
    PERSON brother;   // C++ style structure declaration
    sister.age = 13;   // assign values to members
    brother.age = 7;
    cout << "sister.age = " << sister.age << '\n';
    cout << "brother.age = " << brother.age << '\n';

    CELL my_cell;
    my_cell.character = 1;
    cout << "my_cell.character = " << my_cell.character;
}
// Output:
// sister.age = 13
// brother.age = 7
// my_cell.character = 1

勝手に体裁を整えてくれるわけではなく、自分で整えなければならないようです。

標準出力部抜粋
cout << "sister.age = " << sister.age << '\n';
cout << "brother.age = " << brother.age << '\n';
cout << "my_cell.character = " << my_cell.character;

本題:AIに聞いてみた

黙って自分で整えたら宜しいと叱責されたらば肯うばかりですが、些細なことでも反覆するとなればいっとう煩わしいものです。これを解決する旨い話はないものかとAIに聞いてみたところ、次の通り定義すればよいとのことでした。

構造体に標準出力の体裁を定義する
struct S1 {
    int iValue;
    // ostream に対応した出力演算子のオーバーロード
    friend std::ostream& operator<<(std::ostream& os, const S1& s) {
        return os << "{ iValue: " << s.iValue << " }";
    }
};

つまり、次のようにして簡単に表示できるわけです。

#include <iostream>

struct S1 {
    int iValue;
    friend std::ostream& operator<<(std::ostream& os, const S1& s) {
        return os << "{ iValue: " << s.iValue << " }";
    }
};

struct S2 {
    int* piValue;
    friend std::ostream& operator<<(std::ostream& os, const S2& s) {
        return os << "{ piValue: " << *(s.piValue) << " }";
    }
};

struct S3 {
    int& riValue;
    friend std::ostream& operator<<(std::ostream& os, const S3& s) {
        return os << "{ riValue: " << s.riValue << " }";
    }
};

int main() {
    int i = 30;

    S1 s1 = S1 {i};
    std::cout << "S1 " << s1 << std::endl;

    S2 s2 = S2 {&i};
    std::cout << "S2 " << s2 << std::endl;

    S3 s3 = S3 {i};
    std::cout << "S3 " << s3 << std::endl;

    return 0;
}

実行結果
S1 { iValue: 30 }
S2 { piValue: 30 }
S3 { riValue: 30 }

Discussion