學完物件導向程式設計後可以來了解重載運算子重載,operator overloading也可以叫做運算子覆載,或運算子多載,反正意思差不多,這裡就稱為重載運算子重載,至於為何要使用運算子重載呢?先來看一個例子:
int main(void){
int a = 4, b = 6, c;
c = a + b;
std::cout << c; //output:10
}
這個例子中可以很清楚的看到我用一個「加號」將a和b相加,這當然沒問題,那下面這個例子呢?
#include <iostream>
using namespace std;
class data{
public:
int a,b;
data(int,int);
};
data::data(int x = 0,int y = 0){
a = x;
b = y;
}
int main(){
data d1(3,4), d2(6,3), d3;
d3 = d1 + d2;
return 0;
}
這個例子中會得到一個錯誤,因為此時這個「加號」它不知道該怎麼用,因為在這個class裡有兩個數,程式不知道要加哪一個,此時我們就會用到運算子重載,重新定義一個運算子,那定義方式如下:
#include <iostream>
using namespace std;
class data{
public:
int a,b;
data(int,int);
void print_data();
data operator+(data &y_data){
int a_plus = a + y_data.a;
int b_plus = b + y_data.b;
data z_data(a_plus,b_plus);
return z_data;
}
};
data::data(int x = 0,int y = 0){
a = x;
b = y;
}
int main(){
data d1(3,4), d2(6,3), d3;
d3 = d1 + d2;
cout << d3.a << " " << d3.b << endl;
return 0;
}
此時可以完整解決原本的問題,我們將「加號」定義成第一個物件的a加上第二個物件的b,接著我將它存成z_data,並回傳。
在使用sort()函式時也可以使用運算子重載:
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
class data{
public:
int a,b;
data(int,int);
bool operator < (data &y_data){
if(b < y_data.b);
else return b < y_data.b;
}
};
data::data(int x = 0,int y = 0){
a = x;
b = y;
}
int main(){
data arr[5];
srand(time(NULL));
for(int i = 0;i < 5;i++){
arr[i].a = i;
arr[i].b = rand()%30+1;
}
for(int i = 0;i < 5;i++) cout << arr[i].a << " " << arr[i].b << endl;
sort(arr,arr+5);
cout << "===========" << endl;
for(int i = 0;i < 5;i++)
cout << arr[i].b << " ";
cout << endl;
return 0;
}
此處我們將 <
這個符號重新定義,使我們的sort在比較的時候,能清楚知道如何比較,然而我們這邊這樣定義運算子重載是不太好的,好一點的作法如下:
bool const operator < (data &y_data) const {
if(b < y_data.b);
else return b < y_data.b;
}
我們加入const關鍵詞,因為我們只需得到資料,並不會更改他們的值,所以此處是read-only的功能,且若不小心改到裡面的資料還會出現error告訴我們,更方便除錯。
setarch $(uname –machine) –addr-no-randomize /bin/bash
May 23, 2025When a hardware interrupt occurs, such as from a timer or I/O device, the CPU stops executing the current thread and traps into the kernel, entering the interrupt context to run the appropriate Interrupt Service Routine (ISR). While in this context, the system does not immediately resume the interrupted thread because the interrupt might have changed the overall system state—for example, it could have made another thread ready to run. Since the ISR executes outside of any specific thread's context, the kernel must wait until the interrupt is fully handled before invoking the scheduler to make a fair and informed decision about which thread should run next. This ensures that thread scheduling considers all updated states in the system, rather than blindly resuming the interrupted thread.
May 13, 2025is_prime = n * [1]is_prime[0] = is_prime[1] = 0
Apr 28, 2025image
Apr 20, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up