2017-02-04 39 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 -qualify成員函數:

struct X { 
    int a; 

    void f() const { 
     // a = 42; // illegal 
    } 
}; 
相關問題