2017-12-07 6 views
-2

与えられた行列からある値を減算したいとしましょう。 どうすればそのオペレータに過負荷をかけることができますか?C++演算子のオーバーロード<double> - <Matrix>

main.cppに

Matrix<double> m(10, 5); 

auto r = 1.0 - m; //error: return type specified for 'operator double' 

matrix.hpp

template <typename T> 
class Matrix { 
public: 
    Matrix operator double(T val) { 
    Matrix tmp(rows, cols); 

    for (unsigned int i = 0; i < rows; i++) 
     for (unsigned int j = 0; j < cols; j++) { 
     const unsigned int idx = VecToIdx({i, j}); 
     tmp[idx] = val - this[idx]; 
     } 

    return tmp; 
    } 
} 
+0

を 'オペレータdouble'は'返す必要があります変換演算子でありますdouble''は 'Matrix'ではありません – user463035818

+0

演算子' double'はMatrixをdoubleに変換します。あなたはダブルを取るマトリックスコンストラクタを持つことを意味しましたか? – Arkadiy

+0

できません!しかし、 'operator-(double、Matrix)'をオーバーロードすることができます。 – user1810087

答えて

1

あなたのコードはdoubleからMatrixを引くしようとしているが、あなたの質問には、減算するように求められますa double代わりに。それらは2つの異なる操作です。あなたは本当に何をしたいですか?後者の場合

、あなたは減算演算子ではなく、変換演算子、例えばオーバーロードする必要があります。

template <typename T> 
class Matrix { 
public: 
    Matrix operator- (T val) { 
     Matrix tmp(rows, cols); 
     for (unsigned int i = 0; i < rows; i++) 
      for (unsigned int j = 0; j < cols; j++) { 
       const unsigned int idx = VecToIdx({i, j}); 
       tmp[idx] = (*this)[idx] - val; 
      } 
     return tmp; 
    } 
}; 

Matrix<double> m(10, 5); 

auto r = m - 1.0; 
関連する問題