C ++ overloaded method in derived class

I have the following question:

Assume base class A with method:

A& operator+(A& a) {...}

I also have a derived class B that overloads (or at least should) this method:

A& operator+(B& b) {...}

The problem is that if I want to call something like: b + a (where b is of type B and a is of type A), I get a compilation error. (error C2679: binary '+': an operator was not found that accepts the right operand of type "A" (or there is no acceptable conversion)).

Should this call invoke a base class method? (it looks like he overrides the method ..) If not, then why? Is there a way to fix this (don't tell me to overload the method in B using A &)

Sorry, I do not give examples in formatted text, but I do not know how to format it.

Thanks in advance!

PS Im, - Visual Studio 2010.

+3
4

, . B operator+, , .

operator+ , - . , , :

A operator+(const A &lhs, const A &rhs) { ... }
B operator+(const B &lhs, const B &rhs) { ... }

b + a , a + b. b + b .

"" , B:

using A::operator+;

, . , , . ++ LHS -.

Btw, + , , () . , . + , , , , , .

+2

hiding - - . A:: operator + (A &), B:: operator+. - B:: operator + (A &) , , .

: ++ FAQ Lite, , using.

+3

, -, b + a b.operator+( a ), .

, [] .

:

, , - :
class base
{
public:

  virtual ~base();
  virtual void print( std::ostream& ) const;
};

std::ostream& operator<<( std::ostream& out, const base& b )
{
  b.print( out ); return out;
}

, [const], , .. , a + b = c;.

, , , complex real. - . :

const real operator+( const real&, const real& );
const complex operator+( const complex&, const complex& );

, , :)

+2

. -, + "". +, B, - , , .

However, I suspect (but I can’t say for sure without compiling the test project) that it will actually solve your problem. This is because the standard answer for binary operators is to use static methods that take two parameters in a class. C ++ STL makes extensive use of this technique, and I don’t know the reasons for trying to implement binary operators as instance methods, virtual or not. It is just too confusing, without a real side.

0
source

Source: https://habr.com/ru/post/1729746/


All Articles