一篇文章帶你了解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 周長(zhǎng)
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 類對(duì)象 cir */
Circle cir(3);
cir.Perimeter();
cir.Area();
cout << endl;
/* 創(chuàng)建 Rectangle 類對(duì)象 rec */
Rectangular rec(2, 3);
rec.Perimeter();
rec.Area();
cout << endl;
return 0;
}
運(yùn)行結(jié)果

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

