关于运算符重载
about operator overloading
我的教授让我找出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++委员会的成员,要么不是标准功能提案的粉丝,要么根本不在乎,因为他不需要这个功能。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用