如何在C ++中将操作符作为函数调用 [英] how to call an operator as function in C++

查看:146
本文介绍了如何在C ++中将操作符作为函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用某个类的特定基类的特定运算符。对于简单的函数,它很简单:我只是编写SpecificBaseClass :: function(args);.如何在没有强制欺骗的情况下为操作符实现相同的操作?

I want to call a specific operator of specific base class of some class. For simple functions it's easy: I just write SpecificBaseClass::function( args );. How should I implement the same for operators without casting trickery?

孤立的问题:

 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
 ...

我在GCC4.5.1上收到以下错误

I get the following error on GCC4.5.1

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

谢谢!

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

EDIT improved the example to better illustrate the problem

推荐答案

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

The operator is a nonstatic member function, so you could use

a.A::operator+( b )

但是,对于另一个将 operator + 定义为静态成员函数的类,你试过会是对的。第三类可能会使它成为一个自由函数(可以说是最好的方法),所以 B :: operator +(a,b) a.operator + (b)两者都不正确且运算符+(a,b)是正确的。

However, for another class that defines operator+ as a static member function, what you tried would be correct. And a third class might make it a free function (arguably the best way), so B::operator+(a,b) and a.operator+(b) would both be incorrect and operator+(a,b) would be right.

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

Generally it's best just to use operator syntax a+b unless you know exactly what class it is, and that its implementation will never change. In a template context, writing a+b is a must, and it's essentially impossible to take the address of the overload (the only task that requires naming it) without a lot of work.

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

In your context (a comment to another answer mentions templates), the best solution is

c = static_cast< A const & >( a ) + static_cast< A const & >( b );

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

… the problem is solved by slicing the types to reflect the subproblem, not precisely naming the function you want.

这篇关于如何在C ++中将操作符作为函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆