[C++] const指针 const引用 函数声明中的const参数

文章介绍了C++中的三种const指针类型:固定内存指针、指向const数据的指针和constconst指针,以及如何在函数声明中使用const来控制参数的修改。同时讨论了const引用的概念,以防止函数内部修改传入值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const指针

三种const指针介绍

  1. 指针指向固定的一块内存(不可修改),但可修改该内存中的数据
  2. 指针指向的内存可以改变,但不能修改该内存中的数据
  3. 指针指向的内存以及内存中的数据都不可修改
int main() {
    int x = 30;
    int y = 40;
    cout << "x: " << &x << " " << x << endl;
    cout << "y: " << &y << " " << y << endl;

    int *px = &x;
    cout << "px: " << px << " " << *px << endl;
	
	// 第一种const指针
    int *const px1 = &x;
//    px1 = &y;  // Cannot assign to variable 'px1' with const-qualified type 'int *const'
    *px1 = 31;
    cout << "px1: " << px1 << " " << *px1 << endl;
	
	// 第二种const指针
    const int *px2 = &x;
//    *px2 = 31;  // Read-only variable is not assignable
    px2 = &y;
    cout << "px2: " << px2 << " " << *px2 << endl;
	
	// 第三种const指针
    const int *const px3 = &x;
//    *px3 = 31;
//    px3 = &y;
    return 0;
}

输出:
在这里插入图片描述

函数声明中的const使用

为控制函数中的哪些参数可以被修改,可使用const关键字。

void calc_area(const double* const ptrPi,
               const double* const ptrRadius,
               double* const ptrArea) {
    if (ptrArea && ptrRadius && ptrArea)
        *ptrArea = (*ptrPi) * (*ptrRadius) * (*ptrRadius);
}
int main() {
    const double Pi = 3.1416;
    double radius = 10.5;
    double area = 0;
    calc_area(&Pi, &radius, &area);
    cout << area;
    return 0;
}

其中,ptrRadiusptrPi被声明为“指向const数据的const指针”。而ptrArea是用于存储输出的参数,因此不能修改该指针的值(地址),但可修改其指向的数据。

const引用

函数声明中,将参数设置为引用可以避免由实参到形参的复制操作。
同时,为避免在函数内对传入值进行修改,使用关键字const将引用声明为const引用。

void get_square(const int &n, int &res) {
    res = n * n;
}
int main() {
    int num = 27, res = 0;
    get_square(num, res);
    cout << res << endl;
    return 0;
}

参考:《21天学通C++(第8版)》

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值