Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ความหมายของ const ท้ายฟังก์ชันใน C++: Const Member Function

เมื่อเห็น const อยู่ **ท้าย Declaration ของ Member Function** หมายถึง Const Member Function ซึ่งรับประกันว่า Function นั้น ไม่แก้ไข Non-static Data Members ของ Object

Syntax


class MyClass {
    int value_;
public:
    // const ท้าย Function Declaration
    int getValue() const { 
        // value_ = 10; // Compile Error: Cannot modify member in const function
        return value_; 
    }
    
    void setValue(int v) { // Non-const
        value_ = v;
    }
};

กฎของ Const Member Function

  1. ไม่สามารถ Modify Non-static Data Members ได้
  2. สามารถเรียก Const Member Functions อื่นๆ เท่านั้น
  3. สามารถ Modify mutable Members ได้
  4. สามารถ Modify static Members ได้ (เพราะไม่ผูกกับ Instance)

ตัวอย่าง: Const Object เรียกได้เฉพาะ Const Functions


#include <iostream>

class MyClass {
    int value_;
    mutable int cache_; // Mutable: แก้ได้ใน Const Function
    mutable bool cached_;
    
public:
    MyClass(int v) : value_(v), cache_(0), cached_(false) {}
    
    // Const Function: อ่านได้, เขียน mutable ได้
    int getValue() const {
        if (!cached_) {
            cache_ = computeExpensive(); // OK: mutable
            cached_ = true;
        }
        return cache_;
    }
    
    // Non-Const Function: เขียนได้
    void setValue(int v) { 
        value_ = v; 
        cached_ = false; // Invalidate Cache
    }
    
private:
    int computeExpensive() const { return value_ * 2; }
};

int main() {
    const MyClass obj(10); // Const Object
    
    std::cout << obj.getValue() << '\n'; // OK: Const Function
    // obj.setValue(20); // Error: Cannot call non-const on const object
    
    MyClass obj2(5);
    obj2.setValue(20); // OK: Non-const Object
    std::cout << obj2.getValue() << '\n';
}

Const Overloading

สามารถ Overload ได้โดยแยก Const และ Non-const Versions


class Container {
    std::vector data_;
public:
    // Const Version: Read-Only Access
    const int& operator[](size_t i) const { return data_[i]; }
    
    // Non-Const Version: Read-Write Access
    int& operator[](size_t i) { return data_[i]; }
};

int main() {
    const Container c = {1,2,3};
    std::cout << c[0]; // Calls Const Version
    
    Container nc = {1,2,3};
    nc[0] = 10; // Calls Non-Const Version
}

Const Pointer/Reference Parameters


// Pointer to Const: ฟังก์ชันไม่แก้ Object ที่ชี้ได้
void print(const MyClass* ptr);

// Reference to Const: เหมือนข้างต้น แต่ Syntax สะดวกกว่า
void print(const MyClass& ref);

สรุป

  • const ท้าย Member Function = Const Member Function (Read-Only Interface)
  • Const Objects เรียกได้เฉพาะ Const Functions
  • ใช้ mutable สำหรับ Internal State ที่เปลี่ยนได้ใน Const Context (Cache, Lock, Statistics)
  • Const Overloading: จัดเตรียม Const และ Non-const Versions สำหรับ Accessors
  • Best Practice: Mark Functions Const เมื่อเป็นไปได้ (Const Correctness)