串联不同的操作符

Catenate different operators

本文关键字:操作符      更新时间:2023-10-16

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

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 
}

我错过什么了吗?

谢谢你的帮助!

由于运算符优先,表达式

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

被计算为

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

,你的编译器抱怨缺乏有效的operator<<(int, const char[5])

你需要使用括号来改变优先级:

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

也就是说,很难理解这里发生了什么,应该使用操作符来使事情更清晰,而不是更难阅读。