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

Function Overloading และ const Keyword ใน C++

C++ อนุญาต overload ระหว่าง const และ non-const member functions ตาม cv-qualifier ของ object

Overload ตาม const-ness ของ Object

class MyClass {
public:
    void func() const { cout << "const func\n"; }
    void func() { cout << "non-const func\n"; }
};

int main() {
    MyClass obj;
    const MyClass cobj;
    obj.func();  // เรียก non-const version
    cobj.func(); // เรียก const version
}

Overload ตาม Parameter const (Error)

ไม่สามารถ overload แค่ต่างที่ const ของ parameter by-value ได้

void func(const int x); // Error: cannot overload
void func(int x);       // กับนี้ (เหมือนกันหลัง decay)

Overload ตาม Parameter const Pointer/Reference (OK)

void func(const int* x); // OK: ต่างที่ pointer-to-const
void func(int* x);       // OK: ต่างที่ pointer-to-non-const

int x = 10;
obj.func(&x); // เรียก non-const version

กฎ: const ของ parameter by-value ถูก ignore สำหรับ overload resolution แต่ const ของ pointer/reference เป็น signature ที่แตกต่างกัน