Catenate不同的运营商

时间:2014-06-12 08:01:45

标签: c++ operator-overloading operator-keyword operator-precedence

我正在尝试实现一个支持与不同运算符连接的类:

class MyClass {
public:

template<typename T>
MyClass &operator<<(const T& val ) {
  //do something with val
  return *this;
}

template<typename T>
MyClass &operator=(const T& val) {
  //do something with val
  return *this;
} 

};

int main() {
  MyClass a;
  a << "hallo" = 3 << "huuh"; //compiler will complain about 
}

我在这里想念一下吗?

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:4)

由于operator precedence,表达式

a << "hallo" = 3 << "huuh";

评估为

(a << "hallo") = (3 << "huuh");

并且您的编译器抱怨缺少有效的operator<<(int, const char[5])

您需要使用括号来更改优先级:

(a << "hallo" = 3) << "huuh";

也就是说,要理解这里发生的事情是非常困难的,运营商应该习惯于让事情更清晰,更难以阅读。

相关问题