【问题标题】:What's the correct in templated class forward function declaration, operator> overloading模板类前向函数声明,运算符>重载中正确的是什么
【发布时间】:2021-05-23 18:49:20
【问题描述】:

我正在尝试重载类中的运算符,但不知道类中前向声明性函数(如运算符)的正确语法。

operators

    template <typename S, typename T, typename R>
    class TRIPLE
       {
          public:
                   TRIPLE(S, T, R);
                   const TRIPLE &operator=(const TRIPLE &other); // ok
                   TRIPLE friend bool &operator> (const TRIPLE &t1, const TRIPLE &t2); // not ok
    
                   S getFirst();
                   T getSecond();
    
                   void setFirst(S);
                   void setSecond(T);
    
          private:
                   S *first;
                   T *second;
                   R *third;
       };
    
    template <typename S, typename T, typename R>
    TRIPLE<S, T, R>::TRIPLE(S x, T y, R z) : first(x), second(y), third(z) {};
    
    template <typename S, typename T, typename R>
const TRIPLE<S, T, R> &TRIPLE<S, T, R>::operator=(const TRIPLE<S, T, R> &other){
    // all good.
}
    
    template <typename S, typename T, typename R>
const TRIPLE<S, T, R> &TRIPLE<S, T, R>::operator>(TRIPLE<S, T, R> &lhs, TRIPLE<S, T, R> &rhs){
    // error: overloaded 'operator>' must be a binary operator (has 3 parameters)
}

我尝试了各种方法:

TRIPLE friend bool &operator> (const TRIPLE &t1, const TRIPLE &t2);
const TRIPLE  bool &operator> (const TRIPLE &t1, const TRIPLE &t2);
const TRIPLE friend bool &operator> (const TRIPLE &t1, const TRIPLE &t2);

编辑:

bool operator>(const TRIPLE &right) const;

没有错误,但是...

template <typename S, typename T, typename R>
bool operator>(TRIPLE<S, T, R> &rhs){
    return rhs; // just for test
}

错误:重载的 'operator>' 必须是二元运算符(有 1 个参数)

【问题讨论】:

    标签: c++ operator-overloading forward-declaration


    【解决方案1】:

    您必须区分成员和非成员运算符。

    成员运算符> 接受一个参数(操作数为*thisright):

    bool TRIPLE::operator>(const TRIPLE& right) const;
    

    非成员运算符 > 接受两个参数(操作数是 leftright):

    bool operator>(const TRIPLE& left, const TRIPLE& right);
    

    按照惯例,以相同方式使用两个操作数的二元运算符(例如 +、-、>、

    此外,您在没有意义的地方过度使用TRIPLE。我相信你对赋值运算符的规范形式是TRIPLE&amp; operator=(const TRIPLE&amp;)这一事实感到困惑。开头的 TRIPLE&amp; 并不是识别运算符的神奇方法,它实际上是它的返回值(如果你不包含 return *this; ,你的编译器也会抱怨)

    最后,您几乎肯定希望从运营商那里返回bool,而不是bool&amp;。后者,如果不引起未定义的行为(悬空引用),就不是对运算符的直观使用,这样就扼杀了运算符重载的目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多