const int a = 10; int const b = 20;
const chsr* p = "qwerty"; //const用于修饰常量静态字符串
const int * n = &a; int const * n = &a;
const int *n = &a; *n = b;
int c = 3; const int *n = &a; a = 10; a = c;
int a = 1; int b = 2; const int *n = &a; n = &b;
int a = 1; int b = 2; int * const n = &a; *n = b; b = a;
int a = 1; int b = 2; int c = 3; int * const n = &a; n = &b;
const int * const p= &a; int const * const p= &a;
int a = 1; int const &a = b; const int &a = b;
void StrCopy(char *strdes, const char *strsrc);//防止修改指针指向的内容
void swap ( int * const p1 , int * const p2 ) //防止修改指针指向的地址
void test ( const int * const p1 , const int * const p2 ) //以上两种的结合
void function(const Class& Var); //引用参数在函数内不可以改变 void function(const TYPE& Var); //引用参数在函数内为常量不可变
const int * fun2() //调用时 const int *pValue = fun2();
//我们可以把fun2()看作成一个变量,即指针内容不可变。
c.int* const fun3() //调用时 int * const pValue = fun2();
//我们可以把fun2()看作成一个变量,即指针本身不可变。
const int fun1() //这个其实无意义,因为参数返回本身就是赋值。
class A
{
public:
A(int x) : a(x) // 正确
{
//a = x; // 错误
}
private:
const int a;
};
class A
{
public:
int& getValue() const
{
// a = 10; // 错误
return a;
}
private:
int a; // 非const成员变量
};
class A
{
public:
void funcA() {}
void funcB() const {}
};
int main
{
const A a;
a.funcB(); // 正确
a.funcA(); // X
const A* b = new A();
b->funcB(); // 正确
b->funcA(); // X
}
class A
{
public:
void func() {}
void func() const {} // 重载
};
class A
{
public:
A(int size)
: _size(size) // 正确
{}
private:
const int _size;
};
A a(10); //对象a的_size值为10
A b(20); //对象b的_size值为20
class A
{
public:
enum{SIZE1 = 10, SIZE2 = 20};//枚举常量
private:
int arr1[SIZE1];
int arr2[SIZE2];
};
//例子:
void f(const int i) { .........} //对传入的参数进行类型检查,不匹配进行提示
#define PI 3.14159 //常量宏
const doulbe Pi=3.14159; //此时并未将Pi放入ROM中
......
double i=Pi; //此时为Pi分配内存,以后不再分配!
double I=PI; //编译期间进行宏替换,分配内存
double j=Pi; //没有内存分配
double J=PI; //再进行宏替换,又一次分配内存!
void f(const int i) { i=10;//error! } //如果在函数体内修改了i,编译器就会报错
class A
{
......
void f(int i) {......} //一个函数
void f(int i) const {......} //上一个函数的重载
......
};
void f1 ()
{
#define N 12
const int n 12;
}
void f2 ()
{
cout<<N <<endl; //正确,N已经定义过,不受定义域限制
cout<<n <<endl; //错误,n定义域只在f1函数中。若想在f2中使用需定义为全局的
}
void func()
{
const int a = 10;
int* p = const_cast<int*> (&a);
*p = 20;
std::cout<<*p; // 20
std::cout<<a; // 10
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有