Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于运算符重载 我的教授让我找出C++中哪些运算符不能重载,原因是什么。我发现点(.)、范围解析(:)、条件(?:)、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; }_C++_Operator Overloading - Fatal编程技术网

关于运算符重载 我的教授让我找出C++中哪些运算符不能重载,原因是什么。我发现点(.)、范围解析(:)、条件(?:)、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; }

关于运算符重载 我的教授让我找出C++中哪些运算符不能重载,原因是什么。我发现点(.)、范围解析(:)、条件(?:)、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; },c++,operator-overloading,C++,Operator Overloading,在编写上述代码段时,我问了自己几个问题,这些代码段肯定无法编译: 操作员的返回类型应该是什么 它应该采用什么参数 我如何处理我扔的箱子 为什么我需要运行时开销来计算编译时成员 其他开发人员会同意我通过交换成员来四处闲逛吗 这个名单还可以继续下去 这就是为什么不能重载点(.)运算符的原因,通过尝试重载不可重载的运算符,您会问自己一些类似的问题 聪明的头脑可能会找到这些问题的正确答案,但是这个想法不是天生的,不是C++委员会的成员,不是标准的建议提案的粉丝,或者根本不在乎,因为他不需要这个特性。

在编写上述代码段时,我问了自己几个问题,这些代码段肯定无法编译:

  • 操作员的返回类型应该是什么
  • 它应该采用什么参数
  • 我如何处理我扔的箱子
  • 为什么我需要运行时开销来计算编译时成员
  • 其他开发人员会同意我通过交换成员来四处闲逛吗
  • 这个名单还可以继续下去
这就是为什么不能重载点(.)运算符的原因,通过尝试重载不可重载的运算符,您会问自己一些类似的问题


聪明的头脑可能会找到这些问题的正确答案,但是这个想法不是天生的,不是C++委员会的成员,不是标准的建议提案的粉丝,或者根本不在乎,因为他不需要这个特性。网站上的解释对我来说太难理解了。如果你能更简单地解释它,请做我是C++的创建者,为什么你不想直接从马嘴里说出答案?我告诉你在那个网站上已经解释了对像我这样的人来说是困难的。例如,“Sizeof不能重载,因为内置操作(例如将指针递增到数组中)隐式地依赖于它。”您有具体问题吗?但我们可以重载->运算符,用于更简单的目的。为什么?@AbhijithPHaridas
操作符->
操作符*
操作符组成。
,当你重载
操作符->
时,你只重载了
操作符*
的一部分,事实上,您必须返回一个指针,编译器将取消引用该指针,然后使用它自己的
运算符的本机强大实现。
请参阅。