一篇文章帶你了解C++面向?qū)ο缶幊?-繼承
C++ 面向?qū)ο缶幊?—— 繼承
"Shape" 基類
class Shape {
public:
Shape() { // 構(gòu)造函數(shù)
cout << "Shape -> Constructor" << endl;
}
~Shape() { // 析構(gòu)函數(shù)
cout << "Shape -> Destructor" << endl;
}
void Perimeter() { // 求 Shape 周長
cout << "Shape -> Perimeter" << endl;
}
void Area() { // 求 Shape 面積
cout << "Shape -> Area" << endl;
}
};
"Circle" 派生類
"Circle" 類繼承于 “Shape” 類
class Circle : public Shape {
public:
Circle(int radius) :_r(radius) {
cout << "Circle -> Constructor" << endl;
}
~Circle() {
cout << "Circle -> Destructor" << endl;
}
void Perimeter() {
cout << "Circle -> Perimeter : "
<< 2 * 3.14 * _r << endl; // 圓周率取 3.14
}
void Area() {
cout << "Circle -> Perimeter : "
<< 3.14 * _r * _r << endl; // 圓周率取 3.14
}
private:
int _r;
};
"Rectangular" 派生類
"Rectangular" 類繼承于 “Shape” 類
class Rectangular : public Shape {
public:
Rectangular(int length, int width) :_len(length), _wid(width) {
cout << "Rectangular -> Contructor" << endl;
}
~Rectangular() {
cout << "Rectangular -> Destructor" << endl;
}
void Perimeter() {
cout << "Rectangular -> Perimeter : "
<< 2 * (_len + _wid) << endl;
}
void Area() {
cout << "Rectangular -> Area : "
<< _len * _wid << endl;
}
private:
int _len;
int _wid;
};
"main()" 函數(shù)
int main()
{
/* 創(chuàng)建 Circle 類對象 cir */
Circle cir(3);
cir.Perimeter();
cir.Area();
cout << endl;
/* 創(chuàng)建 Rectangle 類對象 rec */
Rectangular rec(2, 3);
rec.Perimeter();
rec.Area();
cout << endl;
return 0;
}
運行結(jié)果

1.創(chuàng)建派生類對象 :
基類的 Constructor 先執(zhí)行,然后執(zhí)行子類的 Constructor
2.析構(gòu)派生類對象 :
派生類的 Destructor 先執(zhí)行,然后執(zhí)行基類的 Destructor
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
求斐波那契(Fibonacci)數(shù)列通項的七種實現(xiàn)方法
本篇文章是對求斐波那契(Fibonacci)數(shù)列通項的七種實現(xiàn)方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
關(guān)于python調(diào)用c++動態(tài)庫dll時的參數(shù)傳遞問題
這篇文章主要介紹了python調(diào)用c++動態(tài)庫dll時的參數(shù)傳遞,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04
C++使用cuBLAS加速矩陣乘法運算的實現(xiàn)代碼
這篇文章主要介紹了C++使用cuBLAS加速矩陣乘法運算,將cuBLAS庫的乘法運算進行了封裝,方便了算法調(diào)用,具體實現(xiàn)代碼跟隨小編一起看看吧2021-09-09
C/C++?Qt?給ListWidget組件增加右鍵菜單功能
本篇文章給大家介紹ListWidget組件增加一個右鍵菜單,當(dāng)用戶在ListWidget組件中的任意一個子項下右鍵,我們讓其彈出這個菜單,并根據(jù)選擇提供不同的功能,感興趣的朋友跟隨小編一起看看吧2021-11-11
Qt圖形圖像開發(fā)之曲線圖表庫QChart編譯安裝詳細方法與使用實例
這篇文章主要介紹了Qt圖形圖像開發(fā)之曲線圖表庫QChart編譯安裝詳細方法與使用實例,需要的朋友可以參考下2020-03-03

