“const”在C和C ++中有何不同?
变量的const限定如何在C和C ++中有所不同?
来自: “const”只是意味着只读还是更多?
“提出这个问题的原因是这个答案: https : //stackoverflow.com/questions/4024318#4024417其中他声明const”just“在C中意味着只读。我认为所有const都意味着,无论它是C还是C ++。他的意思是什么?“
C中的const
不能用于构建常量表达式。
例如 :
#include int main() { int i = 2; const int C = 2; switch(i) { case C : printf("Hello") ; break; default : printf("World"); } }
在C中不起作用,因为case标签不会减少为整数常量。
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::*
可以改变a
,但是main
可以。 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 A a2
上调用非const
方法。 人们可以抛弃const
......
std::cout << ((A&)a2).getValue() << std::endl; // C-style cast std::cout << const_cast(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
意味着该方法被赋予const A *this
指针,而不是像往常一样的A *this
指针,使得this->cachedComputation
成为一个const int &
并且不能被变异。
const_cast
可以在方法中应用,但更好的方法是更改这个成员的声明。
class A { private: mutable int cachedComputation; };
现在,即使使用const A *this
, this->cachedComputation
也可以在不进行强制转换的情况下进行变异。