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; 会报错
#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; 会报错
相关文章推荐
- c++_const用法2
- const 、static、extern的用法总结
- const 用法
- C++中const用法浅析
- ES6 const用法
- C++关键字const用法详解
- const 用法详解
- iOS 宏(define)与const的正确用法
- C++中const、volatile、mutable的用法
- 语句用法: double & operator[](int i)与double operator[](int i)const两个的差别
- const限定修饰符用法总结(常量,指针,迭代器,函数参数,成员函数)
- const的用法
- C++的const和static的用法
- c++中const用法总结
- C++ 中的const用法整理
- C++中static_cast、const_cast、reinterpret_cast的用法举例,附带举例说明强制类型转换时int和int&的区别
- 关于c++中const的用法
- c++中const的用法详解
- const的一些常用用法
- 常量指针与指针常量(const用法)