传递其他参数时,运算符在c ++中重载

时间:2018-01-19 18:12:57

标签: c++

尝试将参数传递给重载方法, NumericSet<T>* operator + (arma::Mat<T> obj1, int options) 这是可能的,如果是,那么函数调用会是什么样的?

例如,我该怎么转

NumericSet<T> add(arma::Mat<T> mat, int option) 
{ 
    if (option == 1) 
    { 
        arma::Mat<T> sum = this->data + mat; 
        return new NumericSet<T>(sum); 
    } 
    else 
    { 
        this->data = this->data + mat; 
        return this; 
    } 
} 

进入正确的operator+

谢谢!

1 个答案:

答案 0 :(得分:1)

your comment code看:

NumericSet<T> add(arma::Mat<T> mat, int option) {
    if (option == 1) {
        arma::Mat<T> sum = this->data + mat;
        return new NumericSet<T>(sum);
    } else {
        this->data = this->data + mat;
        return this;
    }
}

看起来您的真正目标是允许突变到位或产生新值。这就是为什么operator+=(用于就地操作)和operator+(用于非就地操作)之间的区别。每the basic operator overloading idioms你真正想要的是重载operator+=(作为成员),然后根据它(作为非成员)重载operator+,这些都是这样的:

template<typename T>
class NumericSet {
    ...
    NumericSet<T>& operator+=(const arma::Mat<T>& mat) {
        // Changed from this->data = this->data + mat
        // As a rule, += is always cheaper than +, so as long as data
        // is solely owned by this, mutating in place is likely to be much more efficient
        this->data += mat;
        return *this;
    }
}
template<typename T>
inline NumericSet<T> operator+(NumericSet<T> lhs, const arma::Mat<T>& rhs)
{
  lhs += rhs;
  return lhs;
}

现在,当您使用其他+值时,可以使用option=1+=