C++中的const关键字

一、const引用

1. 例子一

复制代码
#include <iostream>
using namespace std;

class sp {

public:
    sp() {cout<<"sp()"<<endl;}
    sp(sp *other) {
        cout<<"sp(sp *other)"<<endl;
    }
    /*
     * 此例子中这个拷贝构造函数要么不存在,
     * 只要存在参数必须加const修饰。
     */
    sp(const sp &other) {
        cout<<"sp(sp &other)"<<endl;
    }
    ~sp() {
        cout<<"~sp()"<<endl;
    }
};

int main(int argc, char **argv)
{
    sp other = new sp();
    return 0;
}
复制代码

执行结果:

sp()
sp(sp *other)
~sp()

1.拷贝构造函数没有使用但是其参数必须是const引用的原因

sp other = new sp();
① new sp()生成一个sp*的临时指针变量。
② 然后使用这个临时的sp*为参数调用构造函数sp(sp *other)构造出一个临时的sp对象。
③ 使用这个临时的sp对象来调用拷贝构造函数来初始化sp other。
由于此例中拷贝构造函数的参数传递的是一个sp的临时变量,所有需要是const引用。

从执行结果上拷贝构造函数的确没有调用,那是高版本的编译器做了优化,但是在编译期编译器仍然做了检查,所以会报这个错!

2.const引用就不可再拷贝构造函数中修改参数other的成员了(read only), 也不存在这个需求。

3.另一个例子

int a = 11;
int &b = a++;

编译报错: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ ,修复:

int a = 11;
const int &b = a++;

 

 

二、在函数名前后加const

(1)在函数名后加const:
只有类的成员函数才能在函数名后面加上const,此时这个成员函数叫做常量成员函数
常量成员函数在执行期间不能修改对象的成员变量的值(静态成员变量除外),也不能调用同类对象的非常量成员函数(同样的静态成员函数除外)。

(2)而在函数名前加const则表示函数的返回值为常量。

 

posted on   Hello-World3  阅读(211)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示