實驗目的
1.掌握C+ +語言多型性的基本概念
2.掌握運算子多載函式的宣告和定義方法
實驗內容
撰寫一個程式,實作復數的乘法,
多型性
在面向物件方法中,所謂多型性就是不同物件收到相同訊息,產生不同的行為,在C++程式設計中,多型性是指用一個名字定義不同的函式,這些函式執行不同但又類似的操作,這樣就可以用同一個函式名呼叫不同內容的函式,
運算子多載函式
系統已定義的運算子不適用于新的自定義資料型別,為了解決這一問題,C++允許運算子的多載,
運算子的多載是通過創建運算子多載函式來實作的;
運算子多載函式多載方法:
●類外定義普通函式
●類內定義成員函式
●友元函式
- 用類外定義運算子多載函式撰寫*
#include<iostream>
using namespace std;
class complex {
public:
double real;
double imag;
complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
void print();
void input(complex );
};
//類外定義
complex operator*(complex co1, complex co2) {
complex temp;
temp.real = co1.real * co2.real - co1.imag * co2.imag;
temp.imag = co1.real * co2.imag + co1.imag * co2.real;
return temp;
}
void complex:: print() {
cout << "mcl real=" << real << " " << "mcl imag=" << imag << endl;
}
void complex::input(complex co1) {
cout << "請輸入實部";
cin >> real;
cout << "請輸入虛部";
cin >> imag;
}
類外定義運算子多載函式不屬于任何類,只能訪問類中的公有成員資料,
2.用成員運算子多載函式撰寫*
#include<iostream>
using namespace std;
class complex {
public:
double real;
double imag;
complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
void print();
void input(complex );
complex operator*(complex c);//類內成員函式
};
complex complex :: operator*(complex c) {
complex temp;
temp.real = real * c.real - imag * c.imag;
temp.imag = real * c.imag + imag * c.real;
return temp;
}
成員運算子多載函式可以訪問類內的私有成員或保護成員,
在成員運算子多載函式的形參表中:
?如果運算子是單目的,則引數表為空;
?如果運算子是雙目的,則引數表中有一個運算元,
對雙目運算子而言,成員運算子多載函式的形參表中僅有一個引數,是運算子的右運算元,另一個運算元(左運算元)是隱含的this指標,當前物件,
3.用友元運算子多載函式撰寫*
#include<iostream>
using namespace std;
class complex {
public:
double real;
double imag;
complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
void print();
void input(complex );
friend complex operator*(complex co1, complex co2);
//友元函式
};
complex operator*(complex co1, complex co2) {
complex temp;
temp.real = co1.real * co2.real - co1.imag * co2.imag;
temp.imag = co1.real * co2.imag + co1.imag * co2.real;
return temp;
}
友元運算子多載函式可以訪問類內的私有成員或保護成員,但不屬于類內,
運算子多載函式說明:
不能多載的運算子:
. 成員訪問運算子
.* 成員訪問指標運算子
? : 條件運算子
:: 作用域運算子
sizeof 長度運算子
C++只能對已有的C++運算子進行多載,不允許用戶自定義新的運算子,
運算子多載是針對新型別資料的實際需要,對原有運算子進行適當的改造完成的,
運算子多載不改變操作物件目數:
“+”為雙目運算子,多載后依舊是雙目運算子,
運算子多載不改變優先級,
運算子運算子多載函式的引數至少應有一個是類物件(或類的參考),
程式執行結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/384525.html
標籤:其他
上一篇:西郵Linux2019面試題
下一篇:C語言——運算子
