微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模板化类前向函数声明中的正确之处是什么,运算符> 重载

如何解决模板化类前向函数声明中的正确之处是什么,运算符> 重载

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

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 R>
    TRIPLE<S,R>::TRIPLE(S x,T y,R z) : first(x),second(y),third(z) {};
    
    template <typename S,typename R>
const TRIPLE<S,R> &TRIPLE<S,R>::operator=(const TRIPLE<S,R> &other){
    // all good.
}
    
    template <typename S,R>::operator>(TRIPLE<S,R> &lhs,TRIPLE<S,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 R>
bool operator>(TRIPLE<S,R> &rhs){
    return rhs; // just for test
}

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

解决方法

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

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

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

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

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

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

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

最后,您几乎肯定希望从运算符返回 bool,而不是 bool&。后者,如果不引起未定义的行为(悬空引用),则不是操作符的直观使用,这会扼杀操作符重载的目的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。