深入理解C++ const 关键字<四>修饰类的成员函数

📅 2026/8/21 6:33:57
深入理解C++ const 关键字<四>修饰类的成员函数
这是C面向对象中极其重要的特性。在函数声明末尾加const表示该函数承诺不会修改调用它的对象即this指向的对象。性质const对象只能调用const成员函数。重载可以同时存在const和非const版本const对象调用const版本非const对象调用非const版本读写分离设计。#include iostream #include string class Data { private: int value_; std::string name_; public: Data(int val, const std::string name) : value_(val), name_(name) {} // ---------- 非 const 版本可修改对象 ---------- // 返回非常量引用允许调用者修改 value_ int getValue() { std::cout 非 const getValue() 被调用 std::endl; return value_; } // 设置 value仅非 const 可调用 void setValue(int newVal) { value_ newVal; std::cout setValue() 被调用新值 newVal std::endl; } // ---------- const 版本只读访问 ---------- // 返回常量引用承诺不修改对象 const int getValue() const { std::cout const getValue() 被调用 std::endl; return value_; } // 获取 name只读仅提供 const 版本也可但为了演示重载也提供两个版本 const std::string getName() const { std::cout const getName() 被调用 std::endl; return name_; } // 非 const 版本可选此处为了演示重载 std::string getName() { std::cout 非 const getName() 被调用 std::endl; return name_; } // 一个 const 成员函数展示其不能修改成员变量编译期保证 void print() const { std::cout Data{ name name_ , value value_ } std::endl; // value_ 100; // 编译错误表达式必须是可修改的左值因为 this 是 const } }; int main() { // 1. 非 const 对象 Data obj(42, example); std::cout 非 const 对象调用 std::endl; // 调用非 const 版本可读写 obj.getValue() 100; // 返回 int可赋值 std::cout 修改后 value obj.getValue() std::endl; // 再次调用 getValue仍然是非 const 版本 obj.setValue(200); obj.getName() modified; // 非 const getName() 返回 std::string可修改 obj.print(); // 2. const 对象 const Data constObj(999, const_example); std::cout \n const 对象调用 std::endl; // const 对象只能调用 const 成员函数 int val constObj.getValue(); // 调用 const getValue() std::string name constObj.getName(); // 调用 const getName() constObj.print(); // print() 是 const可调用 // 下面这行编译错误因为 setValue 不是 const // constObj.setValue(123); // 错误对象有 const 限定符但成员函数没有 const // 下面这行编译错误因为非 const getValue() 返回 int但 const 对象不能调用 // constObj.getValue() 500; // 错误const 对象不能调用非 const 版本 // 3. 演示重载决议通过引用或指针const 版本会被选择 std::cout \n 通过 const 引用调用 std::endl; const Data ref obj; // 将非 const 对象绑定到 const 引用 ref.getValue(); // 调用 const getValue()因为 ref 是 const 限定 // ref.setValue(300); // 错误const 引用不能调用非 const 成员 std::cout \n 通过非 const 引用调用 std::endl; Data nonConstRef obj; nonConstRef.getValue(); // 调用非 const getValue() return 0; }