classとconst宣言
C++メモ(個人的なメモです.間違っているかも)
constメンバ関数
constメンバ関数は, オブジェクト内部が変更されない事を宣言する(ただしconst_cast指定された場合を除く:追記中)
そのためconstメンバ関数でメンバ変数を変更する記述は,コンパイルエラーとなる
class ABC{
private:
int value;
public:
ABC() : value(0){} // Default Constructor
ABC(const ABC &abc): value(0){ // Copy Constructor
value = abc.value;
}
ABC(int val) : value(val){
cout << "preset(value) = " << value << endl;
}
///
void add(int val){ // 非const関数
value += val;
cout << "add value = " << value << endl;
}
///
void add(int val) const{ // const関数 オブジェクトを変更しない
//value += val; // コンパイルエラー
cout << "value = " << value << endl;
}
};
const修飾されたクラスオブジェクト変数 と,constメンバ関数
const修飾されたクラスオブジェクト変数は, オブジェクト内部が改変されない事を保障しなければならない(ただしconst_cast指定された場合を除く:追記中)
そこで C++ではこのような場合,その constメンバ関数のみの呼出しのみ許可することによって行っている.
# include<iostream>
using namespace std;
class ABC{
private:
int value;
public:
ABC() : value(0){} // Default Constructor
ABC(const ABC &abc): value(0){ // Copy Constructor
value = abc.value;
}
ABC(int val) : value(val){
cout << "preset(value) = " << value << endl;
}
void add(int val){ // 非const版 add()関数
value += val;
cout << "[ ]add value = " << value << endl;
}
void add(int val) const{ // const版 add()関数 オブジェクトを変更しない
//value += val; // コンパイルエラー
cout << "[Const]add value = " << value << endl;
}
};
///
///
int main(){
ABC abc(100); // const修飾 なし
const ABC abc_const(200); // const修飾 有り
abc.add(10); // 非const版 add()を呼び出し)
abc_const.add(10); // const版 add()を呼び出し)
// :
// :
};
以下のようにconstメンバ関数の定義箇所を外した状態で,const修飾されたクラスオブジェクト変数を定義すると,コンパイルエラー
# include <iostream>
using namespace std;
class ABC{
private:
int value;
public:
ABC() : value(0){} // Default Constructor
ABC(const ABC &abc): value(0){ // Copy Constructor
value = abc.value;
}
ABC(int val) : value(val){
cout << "preset(value) = " << value << endl;
}
void add(int val){ // 非const関数
value += val;
cout << "add value = " << value << endl;
}
/***
///void add(int val) const{ // const関数 オブジェクトを変更しない
/// //value += val; // コンパイルエラー
/// cout << "value = " << value << endl;
///}
***/
};
///
///
int main(){
ABC abc(100); // OK (非constのaddを呼び出し)
//const ABC abc_const(200); // コンパイルエラー(非constのaddが呼び出されるため,またはconstのaddが無いため)
:
:
};