const
このような宣言におけるの意味は何でしょうか?
class foobar
{
public:
operator int () const;
const char* foo() const;
};
ベストアンサー1
const
メソッドに キーワードを追加すると、this
ポインターは基本的にオブジェクトへのポインターになるためconst
、メンバー データを変更することはできません。( を使用しない限りmutable
、これについては後で詳しく説明します)。
キーワードconst
は関数シグネチャの一部です。つまり、オブジェクトが のときに呼び出されるメソッドconst
と、そうでない場合に呼び出されるメソッドの 2 つの類似したメソッドを実装できます。
#include <iostream>
class MyClass
{
private:
int counter;
public:
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Foo() const
{
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
出力は次のようになります
Foo
Foo const
非 const メソッドではインスタンス メンバーを変更できますが、これはバージョンでは実行できませんconst
。上記の例のメソッド宣言を以下のコードに変更すると、エラーが発生します。
void Foo()
{
counter++; //this works
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; //this will not compile
std::cout << "Foo const" << std::endl;
}
これは完全に正しいわけではありません。メンバーを としてマークしmutable
、メソッドconst
でそれを変更できるからです。これは主に内部カウンターなどに使用されます。その解決策は以下のコードになります。
#include <iostream>
class MyClass
{
private:
mutable int counter;
public:
MyClass() : counter(0) {}
void Foo()
{
counter++;
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; // This works because counter is `mutable`
std::cout << "Foo const" << std::endl;
}
int GetInvocations() const
{
return counter;
}
};
int main(void)
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}
出力は
Foo
Foo const
Foo has been invoked 2 times