C++ 中的 const 关键字

1. 常量变量

const 可用于声明常量变量。常量变量是在初始化后无法更改其值得变量。常量变量必须在声明时进行初始化

const int i = 10;

2. 指向常量的指针

指向常量的指针: 指针指向的内容不能被改变。

const int * u;  // a pointer point to const int
int const * u;  // a pointer to an int which is of const type

3. 常指针

常指针:指针的指向不能被改变。在可以更改值但不能移动内存的情况下很有用。

int x = 1;
int * const w = &x; // a pointer, which is const, that point to an int

4. 指向常量的常指针

指向常量的常指针:指针的指向和指向的内容均不能被改变。

int x = 12;
const int * const m = &x;

5. 函数的参数为常量

传入的参数在函数中不能被改变

void f(const int arg) 
{
    ...
}

6. 函数的返回类型为常量

const int f()
{
    return 1;
}
  • 对于内置数据类型,返回 const 和非 const 值没有任何区别
  • 对于用户定义的数据类型,返回 const 将阻止对其进行修改
  • 程序执行时创建的临时对象始终为 const 类型
  • 如果函数具有非 const 参数,则在调用时不能传入 const 参数
  • 具有 const 类型参数的函数可以传递 const 类型参数和非 const 参数

7. 将类的数据成员定义为 const

它们在声明期间未初始化。它们的初始化在构造函数中完成。

class Test
{
    const int i;
    public:
    Test(int x):i(x)
    {
        cout << "\ni value set: " << i;
    }
};

int main()
{
    Test t(10);
    Test s(20);
}

8. 定义类对象为 const

当使用 const 关键字声明或创建对象时,在其生存期内,其数据成员将永远无法更改。

const Test t(30);

9. 定义类的成员函数为 const

const 成员函数不能修改对象中的数据成员

class StarWars
{
public:
    int i;
    StarWars(int x)    // constructor
    {
        i = x;
    }

    int falcon() const  // constant function
    {
        /* can do anything but will not modify any data members */
        cout << "Falcon has left the Base";
    }

    int gamma()
    {
        i++;
    }
};

int main()
{
    StarWars objOne(10);        // non const object
    const StarWars objTwo(20);      // const object

    objOne.falcon();     // No error
    objTwo.falcon();     // No error

    cout << objOne.i << objTwo.i;

    objOne.gamma();     // No error
    objTwo.gamma();     // Compile time error
}

const 与 #define 的比较

  • #define 是预处理器指令,而 const 是关键字
  • #define 不是范围控制的,而 const 是范围控制的
    • 通过包含相关的头文件,宏可以在程序或其他文件中的任何位置使用
  • #define 可以重新定义,但 const 不能
  • const 定义的变量有类型,而 #define 没有
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值