何'const'なオペレーター()オーバーロード?
-
23-09-2019 - |
質問
いつのデータベース間でデータをマトリックスクラスは、この二つの定義がありま ()
オペレーター:
template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col)
{
......
}
template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const
{
......
}
一つのことを理解しているのは戻りませんの参考にな const
平均の宣言は?またる機能を要求されたときに呼び出されるいい mat(i,j)
?
解決
呼び出される関数
は、インスタンスがconstのかどうかに依存します。最初のバージョンは、インスタンスを変更することができます:
Matrix<int> matrix;
matrix(0, 0) = 10;
あなたはマトリックスのconstのインスタンス(参照)を持っている場合はconstのオーバーロードは、読み取り専用アクセスを許可します。
void foo(const Matrix<int>& m)
{
int i = m(0, 0);
//...
//m(1, 2) = 4; //won't compile
}
の意図がオブジェクトを変更禁止することであるので、第1の参照を返さない(あなたが値のコピーを取得し、従ってマトリックスインスタンスを変更することはできません)。
ここでTは値を返すために安価で簡単な数値型(ER)であることを想定しています。
:Tはまた、より複雑なユーザー定義型であるかもしれない場合はconstのオーバーロードは、const参照を返すようにするために、それはまた、一般的になります template <class T>
class MyContainer
{
//..,
T& operator[](size_t);
const T& operator[](size_t) const;
}
他のヒント
constのバージョンは、constの行列に呼び出されます。 非const行列に非constバージョンが呼び出されます。
Matrix<int> M;
int i = M(1,2); // Calls non-const version since M is not const
M(1,2) = 7; // Calls non-const version since M is not const
const Matrix<int> MConst;
int j = MConst(1,2); // Calls const version since MConst is const
MConst(1,2) = 4; // Calls the const version since MConst is const.
// Probably shouldn't compile .. but might since return value is
// T not const T.
int get_first( const Matrix<int> & m )
{
return m(0,0); // Calls the const version as m is const reference
}
int set_first( Matrix<int> & m )
{
m(0,0) = 1; // Calls the non-const version as m is not const
}
関数が呼び出され、
は、オブジェクトがconst
であるかどうかに依存します。 const
は、オブジェクトのためのconst
の過負荷が呼び出されます:
const Matrix<...> mat;
const Matrix<...>& matRef = mat;
mat( i, j);//const overload is called;
matRef(i, j); //const overloadis called
Matrix<...> mat2;
mat2(i,j);//non-const is called
Matrix<...>& mat2Ref = mat2;
mat2Ref(i,j);//non-const is called
const Matrix<...>& mat2ConstRef = mat2;
mat2ConstRef(i,j);// const is called
同じことがポインタに適用されます。コールはへのポインタのconstを介して行われる場合、constのオーバーロードが呼び出されます。それ以外の場合は非constのオーバーロードが呼び出されます。
所属していません StackOverflow