註明:關於運算符重載的問題,我遇到過很多次,依然沒有記住。痛心疾首!
運算符重載的典型使用:在玩遊戲時彈出來一個廣告,我們點關閉結果打開了廣告,就是代碼定義的是打開給我們顯示的是關閉。
運算符重載:
1.概念:把運算符operator+當做一個函數來看,把對象當做一個複數,來進行實部與實部,虛部與虛部的相加。返回一個對象。
Complex operator + (Complex &c2); // Complex是函數類型,operator+爲函數名,c2爲另一個對象,也就是要操作的對象。
.h文件
#ifndef COMPLEX_H_
#define COMPLEX_H_
//複數
class Complex
{
public:
double i;
double j;
Complex(); //構造函數
Complex(double i, double j); //構造函數
Complex operator + (Complex &c2); //普通函數也就是運算符重載的函數
void show();
};
#endif /* COMPLEX_H_ */
.cpp文件
#include "Complex.h"
#include <iostream>
using namespace std;
Complex::Complex()
{
this->i = 0;
this->j = 0;
}
Complex::Complex(double i,double j) {
this->j = j;
this->i = i;
}
void Complex::show() {
cout<<"i="<<this->i<<":j="<<this->j<<endl;
}
Complex Complex::operator + (Complex &c2) { //進行兩個對象的相加,實部與實部相加,虛部與虛部相加。
Complex c;//c.i==0; c.j==0
c.i = this->i + c2.i;//c.i=1+1.1
c.j = this->j + c2.j;//c.j=2+2.2
//c.i=2.1; c.j=4.2
return c; //返回和的對象
}
//C語言也可以用運算符重載,但是必須加friend或者把變量定義爲public,私有的訪問不到。
main.cpp文件
#include <iostream>
using namespace std;
#include "Complex.h"
void f1()
{
Complex c1(1, 2);//c1.i=1;c1.j=2
Complex c2(1.1, 2.2);//c2.i=1.1;c2.j=2.2
// Complex c3 = c1.operator+(c2);//c3.i=2.1; c3.j=4.2
Complex c3 = c1 + c2;
c3.show();
}
int main() {
f1();
return 0;
}