C++:常量对象为何只能掉调用常量成员函数

1. 原因解析

在 C++ 中,如果一个对象是 const,那么它的成员变量不能被修改。因此,为了保证这一特性,编译器只允许 const 对象调用常量成员函数(即 const 修饰的成员函数),从而防止 const 对象被修改。

常量成员函数是指声明时带有 const 关键字的成员函数,例如:

class MyClass {
public:
    void regularFunction() { // 非常量成员函数
        data = 10;  // 修改数据
    }

    void constFunction() const { // 常量成员函数
        // data = 10;  // ❌ 错误!不能修改数据
    }

private:
    int data;
};

如果 const 对象允许调用 const 成员函数,可能会修改 const 对象的内部数据,违背 const 语义,因此编译器会报错。

2. 代码示例

(1)常量对象只能调用常量成员函数

#include <iostream>
using namespace std;

class MyClass {
public:
    void regularFunction() { 
        cout << "非const成员函数" << endl;
    }

    void constFunction() const { 
        cout << "const成员函数" << endl;
    }
};

int main() {
    const MyClass obj;  // 定义常量对象
    // obj.regularFunction();  // ❌ 编译错误,常量对象不能调用普通成员函数
    obj.constFunction();  // ✅ 允许,常量对象可以调用 const 成员函数

    return 0;
}

输出:

const成员函数

(2)常量对象的引用也只能调用 const 成员函数

void printClass(const MyClass& obj) {
    // obj.regularFunction();  // ❌ 编译错误
    obj.constFunction();  // ✅ 允许
}

objconst MyClass& 类型的引用时,它只能调用 const 成员函数,防止修改原始对象。

3. 结论

  1. 常量对象(const MyClass obj)只能调用 const 成员函数
  2. 常量对象的引用(const MyClass& obj)也只能调用 const 成员函数
  3. const 成员函数不能修改成员变量,除非该变量用 mutable 关键字修饰。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值