这段给出的代码在C语言中可以编译通过,但在C++中无法通过。
int main()
{
const int x; /* uninitialized const compiles in C but fails in C++*/
}
从 C 转向 C++ 的原因和理由是什么?
请查看规范,兼容性附录 C.1.6:
7.1.6 [参见 3.5]
更改: 在 C++ 中 const 对象必须初始化,但在 C 中可以不初始化
原因: const 对象不能被赋值,所以必须初始化为有用的值。
对原始特性的影响: 删除了语义上明确定义的特性。
转换难度: 语义转换。
使用频率: 很少。
const
关键字在1989年的C89中被引入,但自1983年创建以来就一直存在于C++中。因此,它是从C++中“倒退”到C中的。
C和C ++中的初始化语义通常不同。尽管大多数时候它们“只是做您期望的事情”,但在某些情况下,差异变得非常重要。毕竟,C ++真的不是C的超集。
例如,在C ++中,您无法:
goto x;
int i = 3;
x:
puts("Hello, world");
int main()
{
/*Unless explicitly declared extern, a const object does not have
external linkage and must be initialized*/
extern const int x;
return 0;
}
它将被编译。因此,这自我解释了在c++中强制执行此错误的必要性,声明未初始化的const变量和外部链接是无用的,所以程序员一定是因为失误而添加的。
#include<iostream>
using namespace std;
class Test
{
int value;
public:
Test(int v = 0) {value = v;}
int getvalue() const {return value;}
};
int main(){
Test t(20);
cout << t.getvalue();
return 0;
const double P1 = 68.68;
cout<<P1<<endl;
int star = 57;
int const *pstar = ☆
cout<<*pstar<<endl;
return 0;
}
const
块作用域变量提供值。 - Johannes Schaub - litbconst int i; *((int*)&
- Yury