2017-02-04 8 views
-1

クラスに変数があり、そのクラスのメソッドが変数を定数にしないでメンバ変数を変更すべきでないとします。 これはどのように達成できますか?メソッドが独自のクラス変数を定数にすることなく変更する方法

+1

メンバ関数を 'const'にします。 – songyuanyao

+0

これは[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)ですか? – Rakete1111

+1

[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)のように聞こえます。 –

答えて

1

定数メソッドを使用します。例:

class Foo { 
public: 
    // this won't be able to change any member variable 
    void bar() const; 
} 

void Foo::bar() const { 
} 
1

はい。 const - メンバ関数を修飾します。

struct X { 
    int a; 

    void f() const { 
     // a = 42; // illegal 
    } 
}; 
関連する問題