實驗題目:第12章習題4程序驗證
一、實驗?zāi)康?/h2>
- 上機驗證《C++程序設(shè)計(第3版)》第12章習題4皮钠。
- 復(fù)習C++多態(tài)性與虛函數(shù)相關(guān)知識艳汽。
二、實驗內(nèi)容
詳見一震束、實驗?zāi)康?/code>怜庸。
三、設(shè)計和編碼
1. 本實驗用到的理論知識
C++多態(tài)性與虛函數(shù)
2. 編碼
程序清單如下
// ex4.cpp
// Encoding: UTF-8
/*
* 4.定義一個抽象類Shape垢村,由它派上生出3個派生類:Circle(圓形)割疾、
* Rectangle(矩形)、Triangle(三角形)嘉栓,
* 用一個函數(shù)printArea分別輸出以上三者的面積宏榕,3個圖形的數(shù)據(jù)在定義對象時給定。
*/
#include <iostream>
using namespace std;
//定義抽象基類Shape
class Shape
{
public:
virtual double area() const = 0; //純虛函數(shù)
};
//定義Circle類
class Circle : public Shape
{
public:
Circle(double r) : radius(r) {} //構(gòu)造函數(shù)
virtual double area() const { return 3.14159 * radius * radius; }; //定義虛函數(shù)
protected:
double radius; //半徑
};
//定義Rectangle類
class Rectangle : public Shape
{
public:
Rectangle(double w, double h) : width(w), height(h) {} //構(gòu)造函數(shù)
virtual double area() const { return width * height; } //定義虛函數(shù)
protected:
double width, height; //寬與高
};
class Triangle : public Shape
{
public:
Triangle(double w, double h) : width(w), height(h) {} //構(gòu)造函數(shù)
virtual double area() const { return 0.5 * width * height; } //定義虛函數(shù)
protected:
double width, height; //寬與高
};
//輸出面積的函數(shù)
void printArea(const Shape &s)
{
cout << s.area() << endl;
} //輸出s的面積
int main()
{
Circle circle(12.6); //建立Circle類對象circle
cout << "area of circle =";
printArea(circle); //輸出circle的面積
Rectangle rectangle(4.5, 8.4); //建立Rectangle類對象rectangle
cout << "area of rectangle =";
printArea(rectangle); //輸出rectangle的面積
Triangle triangle(4.5, 8.4); //建立Triangle類對象
cout << "area of triangle =";
printArea(triangle); //輸出triangle的面積
return 0;
}
四侵佃、運行與測試
1. 測試環(huán)境
運行環(huán)境:Windows 20H2, i7-9750H @ 2.60GHz, 16GB RAM
編譯器:gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
編譯命令:-g
運行終端:cmd
2. 在調(diào)試程序的過程中遇到的問題與解決方案
暫未發(fā)現(xiàn)異常麻昼。
3. 程序的運行結(jié)果
運行結(jié)果(符合預(yù)期)
D:\OneDrive - mail2.sysu.edu.cn\MyDocuments\code\DSA\week03>ex4
area of circle =498.759
area of rectangle =37.8
area of triangle =18.9
六、總結(jié)與心得
- 多態(tài)性與虛函數(shù)是C++面向?qū)ο蟪绦蛟O(shè)計中重要知識馋辈,不容小覷涌献。
- 在實際編程中,為了實現(xiàn)多態(tài)性首有,且防止內(nèi)存泄漏,在有動態(tài)分配堆上內(nèi)存的時候枢劝,我們需要將析構(gòu)函數(shù)定義成虛函數(shù)井联,但沒有必要是純虛的。
七您旁、參考資料
- 譚浩強. C++程序設(shè)計[M]. 3 版. 清華大學(xué)出版社, 2015.