关于运算符重载

about operator overloading

本文关键字:重载 运算符      更新时间:2023-10-16

我的教授让我找出c++中哪些运算符不能重载,原因是什么。我发现dot(.)、scope resolution(::)、conditional(?:)、sizeof()运算符不能重载。有人能告诉我原因吗?

struct Troll
{
  int money = 0;
  int problems = 0;
  float cant_touch_this = 0.0;
  int& operator.(const std::string& member_name)
  {
    if (member_name == "money")
      return problems;
    else if (member_name == "problems")
      return money;
    else if (member_name == "cant_touch_this")
      throw cant_touch_this;
    else
      throw 0;
  }
};
int main()
{
 Troll t;
 t.money = 42;
 t.problems = 3;
}

在编写上面的代码片段时,我问了自己多个问题:

  • operator.返回类型应该是什么
  • 应该采用什么参数
  • 我该如何处理我扔的箱子
  • 为什么我需要运行时开销来评估编译时成员
  • 其他开发人员会接受我通过切换我的成员来四处闲逛吗
  • 这个列表可以继续

这就是为什么你不能重载dot(.)运算符的原因,当你试图重载不可重载的运算符时,你也会问自己类似的问题。

一个聪明的人可能会找到这些问题的合适答案,但这个人要么还没有出生,要么不是c++委员会的成员,要么不是标准功能提案的粉丝,要么根本不在乎,因为他不需要这个功能。