const
は、を意味します。変数を変更しないことを約束します。それはまだ変更することができます。
class A {
public:
A(const int& a);
int getValue() const;
void setValue(int b);
private:
const int& a;
};
A::A(a) : a(a) {}
int A::getValue() const {
return a;
}
void A::setValue(int b) {
a = b; // error
}
int main() {
int my_a = 0;
A a(my_a);
std::cout << a.getValue() << std::endl; // prints 0
my_a = 42;
std::cout << a.getValue() << std::endl; // prints 42
}
a
が、main
缶を変更することができませんA::*
方法。それはCとC++の間ではほとんど同じです。持っていないどのようなC++
は不適切const
を捨てるからプログラマを阻止することになっているconst
をバイパスするカップル(制限)の方法、です。
このようなクラスをとってください。
class A {
public:
A();
int getValue();
private:
static int expensiveComputation();
int cachedComputation;
};
A::A() : cachedComputation(0) {}
A::getValue() {
if (cachedComputation == 0)
cachedComputation = expensiveComputation();
return cachedComputation;
}
cachedComputation
は暗黙的にthis->cachedComputation
を意味します。これを覚えておいてください。
int main() {
A a1;
const A a2;
std::cout << a1.getValue() << std::endl;
std::cout << a2.getValue() << std::endl; // error
}
a2.getValue()
非const
方法はconst A a2
で呼び出されているため、違法です。コンパイラは唯一const
-nessは、他に何もキャストされていないことを確認しますので、一つは...
std::cout << ((A&)a2).getValue() << std::endl; // C-style cast
std::cout << const_cast<A&>(a2).getValue() << std::endl; // C++-style cast
をconst
-nessを離れ唱えられる第二は、好ましいです。しかし、これはまだ理想的ではありません。代わりに、新しいメソッドがクラスに追加されるはずです。
class A {
public:
int getValue() const;
};
A::getValue() const {
if (cachedComputation == 0)
cachedComputation = expensiveComputation(); // error
return cachedComputation;
}
は今const
方法があるので、a2.getValue()
で結構です。ただし、末尾のconst
は、通常のようにA *this
ポインターではなく、const A *this
ポインターが指定されており、this->cachedComputation
がconst int &
であり、突然変異ができないことを意味します。
const_cast
はメソッド内に適用できますが、このメンバーの宣言を変更する方が良いでしょう。今
class A {
private:
mutable int cachedComputation;
};
、でもconst A *this
で、this->cachedComputation
は、鋳造せずに突然変異させることができます。
http:// stackoverflow。com/questions/455518/how-many-of-the-use-of-const-in-c – karlphillip
@karlphillip:答えではありません。これはC++でのconstの使用を列挙しますが、CとC++の間のconstの違いはリストしません。全然違う。 –
答えがあれば、私はそれを投稿するでしょう。 – karlphillip