为什么称为运算符重载? [英] Why is it called operator overloading?

查看:98
本文介绍了为什么称为运算符重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果定义了以下类 Foo 。据说它超载 一元和号& )运算符:

  class Foo {
public:
Foo * operator&(){return nullptr; }
};

在这种情况下,我认为(无论您能否获得此类对象的地址通过 std :: addressof()和其他惯用技巧),无法访问/选择原始的一元&运算符,该运算符返回被调用对象的地址,我错了吗?



通过重载但是,我知道有一组函数将在编译时根据某些条件选择一个函数。但是这种想法似乎与上述情况不符。



为什么叫 overloading ,而不是 redefining replacing

解决方案

请考虑以下代码:

  int x; 
Foo y;
& x; //内置功能
& y; // y.operator&();

我们有两个不同类型的变量。我们对它们两个都应用相同的& 运算符。对于 x ,它使用内置的地址运算符,而对于 y ,它调用用户定义的函数。 / p>

这正是您所描述的重载:有多个功能(嗯,其中之一是内置功能,并非真正一个函数),然后根据操作数的类型选择它们。


If the following class, Foo, is defined. It is said it overloads the unary ampersand (&) operator:

class Foo {
public:
   Foo* operator&() { return nullptr; }
};

I think in this case, (reglardless of the fact that you can get the address of such an object by means of std::addressof() and other idiomatic tricks) there is no way to access/choose the original unary ampersand operator that returns the address of the object called on, am I wrong?

By overloading however, I understand that there is a set of functions of which one will be selected at compile-time based on some criteria. But this thinking doesn't seem to match the scenario above.

Why is it then called overloading and not something else like redefining or replacing?

解决方案

Consider the following code:

int x;
Foo y;
&x; // built-in functionality
&y; // y.operator&();

We have two variables of different types. We apply the same & operator to both of them. For x it uses the built-in address-of operator whereas for y it calls your user-defined function.

That's exactly what you're describing as overloading: There are multiple functions (well, one of them is the built-in functionality, not really a "function") and they're selected based on the type of the operand.

这篇关于为什么称为运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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