您的位置:首页 > 其它

const的用法

2017-09-16 20:16 211 查看
在other.cpp中

#include<iostream>
using namespace std;
#const int global=5; //加入const 会让global原来的外部的链接型转为内部链接性。
extern const int global=5;
void print(){
cout << global << endl;
}

在main.cpp中
#include<iostream>
using namespace std;
extern const int global;//这里会报错,因为global中只有other.cpp可以用。
int main(){
cout << global << endl;
system("pause");
return 0;
}
若想这个const常量可以被main.cpp中使用,可以按蓝色字体的加个extern就可以了。
注意:若在other.cpp文件中global变量不具有外部链接性,照样可以通过他的函数print()访问
函数默认具有外部链接性!

这里我还想提醒一下。任何变量或数组的赋值,在main()和一些函数外,只能在定义的时候赋值。
不得定义后再赋值。

#include<iostream>
using namespace std;
//extern const int global;
float * pd1 = new float[20];
int s=5;//可以在定义是直接赋值。
//s = 5;错的
int a[100];
//a[1]=3;错的,

int main(){
pd1[3] = 100.0;
cout << pd1[1] << endl;
float * pd2;
pd2 = new float[20];
pd2[0] = 100.00;
cout << *pd2 << endl;
delete pd2;
delete pd1;
system("pause");
return 0;
}

const int * func; //是一个指向int型常量的指针,这个常量不可改变但指针可以改变
int *const func; //将func不可以自加。


这里指向常量的指针可以指向变量。
int a = 10; //变量
const int * ptr = &a;//指向常量的指针可以指向变量。
a = 3;

但是
const int a = 10; //变量const int * ptr = &a;//指向常量的指针可以指向变量。//a = 3; 会报错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  const