Operator Overloading 多載運算子 ให้ operator ทำงานกับ class เองได้ ใช้ keyword operator ตามด้วยสัญลักษณ์
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
class ComplexNum {
private:
int real, imag;
public:
ComplexNum(int r = 0, int i = 0) {
real = r;
imag = i;
}
ComplexNum operator - (ComplexNum const &obj1) {
ComplexNum obj2;
obj2.real = real - obj1.real;
obj2.imag = imag - obj1.imag;
return obj2;
}
void print() {
if(imag >= 0)
cout << real << " + i" << imag << endl;
else
cout << real << " + i(" << imag << ")" << endl;
}
};
int main() {
ComplexNum comp1(15, -2), comp2(5, 10);
cout << "The two complex numbers are:" << endl;
comp1.print();
comp2.print();
cout << "The result of the subtraction is: ";
ComplexNum comp3 = comp1 - comp2;
comp3.print();
}
ผลลัพธ์
The two complex numbers are: 15 + i(-2) 5 + i10 The result of the subtraction is: 10 + i(-12)
อธิบายโค้ดสำคัญ
Class ComplexNum มี real, imag (ส่วนจริง/จินตภาพ) และ constructor:
class ComplexNum {
private:
int real, imag;
public:
ComplexNum(int r = 0, int i = 0) {
real = r;
imag = i;
}
}
Overload operator - :
ComplexNum operator - (ComplexNum const &obj1) {
ComplexNum obj2;
obj2.real = real - obj1.real;
obj2.imag = imag - obj1.imag;
return obj2;
}
ลบ real กับ real, imag กับ imag คืน object ใหม่
print() แสดงผลจัดรูปแบบ + i หรือ + i( ) ถ้าเป็นลบ:
void print() {
if(imag >= 0)
cout << real << " + i" << imag << endl;
else
cout << real << " + i(" << imag << ")" << endl;
}
main() สร้าง comp1, comp2 คำนวณ comp3 = comp1 - comp2 (ใช้ operator - ที่ overload) แสดงผล