如何在C++中将操作符作为函数调用

11 c++ inheritance function operators

我想调用某个类的特定基类的特定运算符.对于简单的功能,这很容易:我只是写SpecificBaseClass::function( args );.如何在没有诡计的情况下为操作员实现相同的操作?

孤立的问题:

 class A
 {
 public:
     A operator+( const A &other ) const {...}
 };

 class B : public A
 {
 public:
     B operator+( const B & other ) const {...}

 };

 ...
  B a, b;
  B c = A::operator+( a, b ); //how this should be implemented? I get an error
 ...
Run Code Online (Sandbox Code Playgroud)

我从GCC4.5.1收到以下错误:

error: no matching function for call to ‘A::operator+(B&, B&)’
note: candidate is: A A::operator+(const A&) const
Run Code Online (Sandbox Code Playgroud)

谢谢!


编辑
我改进了示例以更好地说明问题.

Pot*_*ter 18

运算符是非静态成员函数,因此您可以使用

a.A::operator+( b )
Run Code Online (Sandbox Code Playgroud)

但是,对于另一个定义operator+为静态成员函数的类,您尝试的是正确的.而第三类可能会使它成为一个自由函数(可以说是最好的方法),所以B::operator+(a,b)并且a.operator+(b)都是不正确的并且operator+(a,b)是正确的.

通常,最好只使用运算符语法,a+b除非您确切知道它是什么类,并且它的实现永远不会改变.在模板上下文中,写入a+b是必须的,并且基本上不可能在没有大量工作的情况下获取重载的地址(唯一需要命名的任务).

在您的上下文中(对另一个答案的评论提到模板),最好的解决方案是

c = static_cast< A const & >( a ) + static_cast< A const & >( b );
Run Code Online (Sandbox Code Playgroud)

...问题是通过切片类型来反映子问题来解决的,而不是精确地命名你想要的功能.