★const★


C++ではconstの使い方も追加されています。

前回のプログラムを利用して、新しいconstの使い方を説明します。

<sample program cpp049-01>

#include <iostream>

class Sample {
public:

    void SetValue(const int value);

    int GetValue() const;

private:

    int m_value;
};

int main()
{
    Sample sample;

    sample.SetValue(15);

    std::cout << sample.GetValue() << std::endl;

    return 0;
}

void Sample::SetValue(const int value)
{
    m_value = value;
}

int Sample:: GetValue() const
{
    return m_value;
}

<実行結果>

15
続行するには何かキーを押してください・・・

getter関数の後ろに「const」を付けました。

これは、

 このメンバ関数の中では、メンバ変数を書き換えない

と言う意味です。

試しにメンバ変数m_valueを書き換えようとしてみます。

<sample program cpp049-02>

#include <iostream>

class Sample {
public:

    void SetValue(const int value);

    int GetValue() const;

private:

    int m_value;
};

int main()
{
    Sample sample;

    sample.SetValue(15);

    std::cout << sample.GetValue() << std::endl;

    return 0;
}

void Sample::SetValue(const int value)
{
    m_value = value;
}

int Sample:: GetValue() const
{
    m_value = 21;

    return m_value;
}

<コンパイル結果>

error C3490: 'm_value' は const オブジェクトを通じてアクセスされているため変更できません

エラーになりました。

メンバ変数を書き換えないメンバ関数には必ず「const」を付けるようにしてください。


次へ

戻る

目次へ