c++基础学习(08)--(继承、重载、多态、虚函数)
生活随笔
收集整理的這篇文章主要介紹了
c++基础学习(08)--(继承、重载、多态、虚函数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 目錄
- 1.繼承
- 2.重載
- 3.多態 && 虛函數
目錄
1.繼承
#include <iostream>using namespace std;// 基類 class Shape {public:void setWidth(int w){width = w;}void setHeight(int h){height = h;}protected:int width;int height; };// 派生類 class Rectangle: public Shape {public:int getArea(){ return (width * height); } };int main(void) {Rectangle Rect;Rect.setWidth(5);Rect.setHeight(7);// 輸出對象的面積cout << "Total area: " << Rect.getArea() << endl;return 0; }當上面的代碼被編譯和執行時,它會產生下列結果:
Total area: 35
當上面的代碼被編譯和執行時,它會產生下列結果:
Total area: 35
Total paint cost: $2450
Hello World!
D()
B()
A()
C()
40
~C()
~A()
~B()
~D()
2.重載
#include <iostream> using namespace std;class printData {public:void print(int i) {cout << "整數為: " << i << endl;}void print(double f) {cout << "浮點數為: " << f << endl;}void print(string c) {cout << "字符串為: " << c << endl;} };int main(void) {printData pd;// 輸出整數pd.print(5);// 輸出浮點數pd.print(500.263);// 輸出字符串pd.print("Hello C++");return 0; }當上面的代碼被編譯和執行時,它會產生下列結果:
整數為: 5
浮點數為: 500.263
字符串為: Hello C++
當上面的代碼被編譯和執行時,它會產生下列結果:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
當上面的代碼被編譯和執行時,它會產生下列結果:
F: -11 I:-10
F: 5 I:-11
3.多態 && 虛函數
#include <iostream> using namespace std;class Shape {protected:int width, height;public:Shape( int a=0, int b=0){width = a;height = b;}int area(){cout << "Parent class area :" <<endl;return 0;} }; class Rectangle: public Shape{public:Rectangle( int a=0, int b=0):Shape(a, b) { }int area (){ cout << "Rectangle class area :" <<endl;return (width * height); } }; class Triangle: public Shape{public:Triangle( int a=0, int b=0):Shape(a, b) { }int area (){ cout << "Triangle class area :" <<endl;return (width * height / 2); } }; // 程序的主函數 int main( ) {Shape *shape;Rectangle rec(10,7);Triangle tri(10,5);// 存儲矩形的地址shape = &rec;// 調用矩形的求面積函數 areashape->area();// 存儲三角形的地址shape = &tri;// 調用三角形的求面積函數 areashape->area();return 0; }
總結
以上是生活随笔為你收集整理的c++基础学习(08)--(继承、重载、多态、虚函数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 周志华《Machine Learning
- 下一篇: 《C++ Primer 5th》笔记(1