I have been looking through a lot of different examples and explanations, but none has really answered what I am looking for. I have three classes with a method called connect for each one:

class foo { ... }
void foo::connect(bar br) { ... }

class bar { ... }
bar& bar::connect(baz bz) { ... }

class baz { ... }
baz& baz::connect() { ... }

In my main class, I 'connect' them like this:

foo.connect(bar);
bar.connect(baz);
baz.connect();

or:

foo.connect( bar.connect( baz.connect() ) );

(I know this is briefly explained, I can explain it better if needed)

So, I was trying to overload the operator '>>' to have something like this in the main function:

foo >> bar >> baz;

For the first operator it works, so if I simply do the following, it works fine:

foo >> bar.connect(baz.connect);

But, when I set the other '>>' operator g++ returns this error:

error: no match for ‘operator>>’ in ‘operator>>((* & foo), (* & bar)) >> baz.baz::connect()’

I think I'm not overloading the operator '>>' properly:

bar& operator>> (bar &br, baz &bz)
{
  ...
}

Thanks for the help :)

有帮助吗?

解决方案

Operators aren't anything magical: they are just functions spelled in a funny way. That is, your statement

foo >> bar >> baz;

actually just calls [or tries to call]

operator>> (operator>> (foo, bar), baz);

That is, you need the operators

bar& operator>> (foo& f, bar& b) {
    f.connect(b);
    return b;
}
bar& operator>> (bar& b0, baz& b1) {
    return b0.connect(b1);
}

Note, that the last connect() you have won't be doable using operator>>() because the operator always takes two arguments.

其他提示

Your overloaded operator takes bar& as its left-hand operand and baz& as its right-hand operand, but your sample code:

foo >> bar.connect(baz.connect);

Has a foo& as the left-hand operand and a bar& as the right-hand operand. Do you also define another version of operator>>?

Also note that, quoting from your sample code, this:

foo.connect(bar);
bar.connect(baz);
baz.connect();

Is NOT the same as this:

foo.connect( bar.connect( baz.connect() ) );

The order of operations is different; in the second example, baz.connect() runs first, followed by bar.connect() and so on. This is opposite of the first example. This may not matter in your application but it's something to consider.

Although you haven't shown it, evidence suggests that your other operator is the problem. That it looks something like this:

foo& operator>>(foo&, bar&) { ... }

But in order for this to work:

foo >> bar >> baz;

You probably want foo >> bar to return the bar (not the foo), so that the next call is this function:

??? operator>>(bar&, baz&) { ... }

And for the sake of consistency, that should probably return baz&, though it is not strictly necessary in this case.

The way you have it (because foo >> bar returns foo), the second operator>> is trying to call this (I'm assuming non-existent) function:

??? operator>>(foo&, baz&) { ... }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top