C++.define与const

#define PI 3.14
const float PI = 3.14f;

const修饰变量
//const int I; // 必须初始化常量对象
const int J = 1; 
//++J; // 常量不可计算

const修饰指针
const int* p; p是变量, *p是常量,即p可以任意指向,但不能修改其他指向地址存储的值。
int* const p; p是常量, *p是变量,即p一经指向不可修改,但可以修改其他指向地址存储的值。
int const *p const; p是常量, *p是常量,即p一经指向不可修改,也不能修改其他指向地址存储的值。
重点:用括号括起*p ,看哪个距离const更近,如果 p 更近于const,则p是常量,反之*p是常量。如果const在*p之间,则看哪个与类型更远。

const修饰函数 
1、类成员函数 
class A
{
private:
    int m;
public:
    A() { this->m = 0; }
    A(int m) { this->m = m; }
public:
    int get() const {
        //return ++this->m; // 由于正在通过常量对象访问“m”,因此无法对其进行修改
        return this->m;
}
};
2、函数参数 
int fn(const int a, int b) {
    // ++a; // 常量不可修改。
    ++b;
    return a + b;
}
3、函数返回值
不要轻易的将函数的返回值类型定为const。除了重载操作符外一般不要将返回值类型定为对某个对象的const引用 。
const int fn(int a, int b) {
    return a + b;
}

猜你喜欢

转载自www.cnblogs.com/dailycode/p/12506017.html
今日推荐