c++ const & no_const成员函数

本文详细介绍了C++中const成员函数的概念及其使用场景,包括如何为const对象调用合适的成员函数,以及如何利用mutable关键字使const成员函数能够修改类内的特定变量。

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

const和非no_const成员函数的调用主要正对const和非const变:

#include<iostream>

using namespace std;
class A
{

public:
    void f() const { cout << "const" << endl; }
    void f() { cout << "no-const" << endl; }


private:
    int  a;

};

int main()
{
    A a1;
    a1.f();
    const A a2;
    a2.f();

    system("pause");
    return 0;
}

这里写图片描述

注意:
下面我们对一些细节讨论
1.只有const函数或者只有非const函数

#include<iostream>

using namespace std;
class A
{

public:
    void f() const { cout << "const" << endl; }
    //void f() { cout << "no-const" << endl; }


private:
    int  a;

};

int main()
{
    A a1;
    a1.f();
    const A a2;
    a2.f();

    system("pause");
    return 0;
}

这里写图片描述

#include<iostream>

using namespace std;
class A
{

public:
    //void f() const { cout << "const" << endl; }
    void f() { cout << "no-const" << endl; }


private:
    int  a;

};

int main()
{
    A a1;
    a1.f();
    const A a2;
    a2.f();//对象含有与成员 函数 "A::f" 不兼容的类型限定符    


    system("pause");
    return 0;
}

报错了。
2 cont成员函数不能修改类中定义的变量。

class A
{

public:
    void f() const { num = 100; }//compile_time;表达式必须是可修改的左值    


    void f() { num = 100; }//ok


private:
    int num;

};

报错了。但是我们可以使用关键字mutable来强制完成上面工作;

class A
{

public:
    void f() const { num = 100; }
    void f() { num = 100; }


private:
    mutable int num;


};

这样就ok了

总结:
no_const的变量可以调用const和no_const成员函数(两者都有的话,优先调用no_const成员函数)。const变量只能调用const成员函数,如果没有就会报错。

小技巧

因为const成员函数的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值