详解C++中的const关键字及与C语言中const的区别
const对象默认为文件的局部变量,与其他变量不同,除非特别说明,在全局作用域的const变量时定义该对象的文件局部变量。此变量只存在于那个文件中中,不能别其他文件访问。要是const变量能在其他文件中访问,必须显示的指定extern(c中也是) const的形参重载: #include <iostream> using namespace std; void f(int& a) { cout << "void f(int& a)" << endl; } void f(const int& a) { cout << "void f(const int& a)" << endl; } int main() { int a = 6; int &b = a; const int c = 8; f(a); f(b); f(c); f(3); return 0; } void f(int& a) void f(int& a) void f(const int& a) void f(const int& a) C与C++中const的区别 1.C++中的const正常情况下是看成编译期的常量,编译器并不为const分配空间,只是在编译的时候将期值保存在名字表中,并在适当的时候折合在代码中.所以,以下代码: #include <iostream> using namespace std; int main() { const int a = 1; const int b = 2; int array[ a + b ] = {0}; for (int i = 0; i < sizeof array / sizeof *array; i++) { cout << array[i] << endl; } } 在可以通过编译,并且正常运行.但稍加修改后,放在C编译器中,便会出现错误: #include <stdio.h> int main() { int i; const int a = 1; const int b = 2; int array[ a + b ] = {0}; for (i = 0; i < sizeof array / sizeof *array; i++) { printf("%d",array[i]); } } 错误消息: c:/test1/te.c(8): error C2057: 应输入常数表达式 c:/test1/te.c(8): error C2466: 不能分配常数大小为 0 的数组 出现这种情况的原因是: const int size; 这个语句是正确的,因为它被C编译器看作一个声明,指明在别的地方分配存储空间.但在C++中这样写是不正确的.C++中const默认是内部连接,如果想在C++中达到以上的效果,必须要用extern关键字. 2.C++中,const默认使用内部连接.而C中使用外部连接. header.h const int test = 1; test1.cpp #include <iostream> #include "header.h" using namespace std; int main() { cout << "in test1 :" << test << endl; } test2.cpp #include <iostream> #include "header.h" using namespace std; void print() { cout << "in test2:" << test << endl; } 以上代码编译连接完全不会出问题,但如果把header.h改为: extern const int test = 1; 在连接的时候,便会出现以下错误信息: test2 error LNK2005: "int const test" (?test@@3HB) 已经在 test1.obj 中定义 因为extern关键字告诉C++编译器test会在其他地方引用,所以,C++编译器就会为test创建存储空间,不再是简单的存储在名字表里面.所以,当两个文件同时包含header.h的时候,会发生名字上的冲突. header.h const int test = 1; test1.c #include <stdio.h> #include "header.h" int main() { printf("in test1:%d/n",test); } test2.c #include <stdio.h> #include "header.h" void print() { printf("in test2:%d/n",test); }
错误消息: test3 fatal error LNK1169: 找到一个或多个多重定义的符号 test3 error LNK2005: _test 已经在 test1.obj 中定义 C++中,是否为const分配空间要看具体情况. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |