メンバー関数宣言の末尾にある「const」の意味は何ですか? 質問する

メンバー関数宣言の末尾にある「const」の意味は何ですか? 質問する

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

おすすめ記事