变量的const限定如何在C和C++中有所不同?
"提出这个问题的原因是这个答案:https://stackoverflow.com/questions/4024318#4024417其中他声明const"just"在C中意味着只读.我认为所有const都意味着,无论它是C还是C++.他是什么意思?"
const 在C中不能用于构建常量表达式.
例如 :
#include <stdio.h>
int main()
{
int i = 2;
const int C = 2;
switch(i)
{
case C : printf("Hello") ;
break;
default : printf("World");
}
}
Run Code Online (Sandbox Code Playgroud)
在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
}
Run Code Online (Sandbox Code Playgroud)
没有方法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;
}
Run Code Online (Sandbox Code Playgroud)
cachedComputation含蓄地意味着this->cachedComputation.记住这一点.
int main() {
A a1;
const A a2;
std::cout << a1.getValue() << std::endl;
std::cout << a2.getValue() << std::endl; // error
}
Run Code Online (Sandbox Code Playgroud)
a2.getValue()是非法的,因为const正在调用非方法const A a2.人们可以抛弃const......
std::cout << ((A&)a2).getValue() << std::endl; // C-style cast
std::cout << const_cast<A&>(a2).getValue() << std::endl; // C++-style cast
Run Code Online (Sandbox Code Playgroud)
第二个是首选,因为编译器将检查只有const-ness被转换,没有别的.但是,这仍然不理想.相反,应该有一个新方法添加到类中.
class A {
public:
int getValue() const;
};
A::getValue() const {
if (cachedComputation == 0)
cachedComputation = expensiveComputation(); // error
return cachedComputation;
}
Run Code Online (Sandbox Code Playgroud)
现在有一种const方法,所以a2.getValue()很好.但是,尾随const意味着该方法被赋予一个const A *this指针,而不是A *this像往常一样的指针,使得this->cachedComputation一个const int &不能被改变.
const_cast 可以在方法中应用,但更好的方法是更改此成员的声明.
class A {
private:
mutable int cachedComputation;
};
Run Code Online (Sandbox Code Playgroud)
现在,即使有了const A *this,this->cachedComputation也可以在没有铸造的情况下进行变异.