简体   繁体   中英

Overload the stream insertion operator for nested structures/classes

I want to overload the stream insertion operator for a structure nested within a class. How can I fix this error and make the function to work, or is there any alternative method to implement it?

struct S {
    int a;
    int b;
};

class T {
private:
    S** arrayName;
    int r;
    int c;

public:
    friend ostream& operator << (ostream& _os, const T& _t) {
        for (int i = 0; i < _t.r; i++) {
            for (int j = 0; j < _t.c; j++) {
                _os << _t.arrayName[i][j];
            }
        }
        return _os;
    }
}

If arrayName was just an integer array within class T like:

int arrayName [4][4]; //for example

the current implementation would work. But as arrayName is a pointer to pointer to struct S and acts as a two-dimensional array of struct S , you will need to overload the << operator within struct S to be able to print its members a and b .

So your struct S should now be:

struct S {
    int a;
    int b;
    friend ostream& operator<<(ostream& _os, const S& _s) { 
        _os << _s.a << ' ' << _s.b << endl; 
        return _os; 
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM