详解C++中的const关键字及与C语言中const的区别

2020-01-06 15:00:52刘景俊

此种情况和C中const含义相似:


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分配空间要看具体情况.
如果加上关键字extern或者取const变量地址,则编译器就要为const分配存储空间.
C++中定义常量的时候不再采用define,因为define只做简单的宏替换,并不提供类型检查



注:相关教程知识阅读请移步到C++教程频道。