Iterating over a struct in C++

前端 未结 8 728
说谎
说谎 2020-11-28 07:08

I have a structure

typedef struct A
{
    int a;
    int b;
    char * c;
}aA;

I want to iterate over each an every member of the structure

8条回答
  •  眼角桃花
    2020-11-28 07:40

    You can't iterate over an object's data members. You can use std::ostream's stream insertion operator to print individually however:

    struct A
    {
        int a;
        int b;
        std::string c;
    
        friend std::ostream& operator <<(std::ostream& os, A const& a)
        {
            return os << a.a << '\n'
                      << a.b << '\n'
                      << a.c << '\n';
        }
    };
    

    And inside main:

    int main()
    {
        A a = {5, 10, "apple sauce"};
    
        std::cout << a;
    }
    

    Output:

    5
    10
    apple sauce

    Here is a demo.

提交回复
热议问题