操作符可以用作函数吗? (C ++) [英] Can operators be used as functions? (C++)

查看:149
本文介绍了操作符可以用作函数吗? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与我问过的另一个问题类似,但是我创建了一个表达式类,其工作原理如下:

This is similar to another question I've asked, but, I've created an expression class that works like so:

expression<int, int> exp(10, 11, GreaterThan);
//expression<typename T, typename U> exp(T val1, U val2, oper op);
//where oper is a pointer to bool function(T, U)

是以前定义的函数。我想知道为什么我不能这样做:

where GreaterThan is a previously defined function. And I am wondering why I can't do this:

expression<int, int> exp(10, 11, >);



particularily when > is overloaded as

bool operator>(int a, int a){return (a > b);}

与GreaterThan相同:

which is identical to GreaterThan:

bool GreaterThan(int a, int b){return (a > b);}

返回bool并接受两个参数的函数。

A function that returns bool and takes two arguments.

推荐答案

而不是:

expression<int, int> exp(10, 11, >);

您可以这样做:

expression<int, int> exp(10, 11, operator>);

可以,因为它不适用于整数。但它将适用于其他类型或操作符,你将重载。


你重载的操作符是正常的函数,所以实际上你正在使用函数指针。

You could because it doesn't work for integers. But it will work for other types or operators that you will overload.

The operators that you overload are normal functions, so actually you are playing with function pointers.

这篇关于操作符可以用作函数吗? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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