开发者

Overloading '<<' so it is usable with more than one object

I'm starting to get a grasp of operator overloading but I开发者_运维知识库've hit a wall. I cant figure out how I would make '<<' work the way it is redefined to work with more than one type of object from my class. I have to use one of my class constructors to initialize two separate matrices so I need to make two different objects like so: matrix a(sizeIn, rangeIn), b(sizeIn, rangeIn); but as you can see below my '<<' overloading function only uses one class parameter. Can anyone help me out?

ostream & operator << (ostream & os, const matrix & a)
{
    for (int i = 0; i < a.size; i++)

    {
        cout << '|';
        for (int j = 0; j < a.size; j++)
            {
            os << setw(4) << a.array[i][j] << " ";
            }
        os << setw(2) << '|' << endl;
    }
    return os;
}


This will work with more than one object because the << overload returns a reference to the stream. << is evaluated1 left to right, so if you do:

stream << a << b << c;

it is equivalent to:

((stream << a) << b) << c;

now, since your (stream << a) function returns an ostream&, we could think of this as:

((stream) << b) << c;

and so on :)

1: technically, it 'associates' left to right, leading to left-to-right evaluation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜