例、编写一个程序,要求计算三角形、正方形的面积,抽象出一个基类base,在其中说明一个虚函数display( )
用来展示其参数且求出面积。
代码如下:
头文件headfile.h:
#pragma once //只运行一次头文件 #include <iostream> using namespace std; class base { public: virtual void display() = 0; //成员函数dispaly()声明为纯虚函数 }; class Square : virtual public base //派生类Square正方形 { protected: float x; public: float width; Square() { } Square(float a) { x = a; } virtual float getSquare() { return (x * x); } virtual void display() { cout << "正方形的边长为:" << x << endl; cout << "正方形的面积为:" << getSquare() << endl; } }; class Rectangle : virtual public base //派生类Rectangle三角形 { protected: int a, h; public: Rectangle() { } Rectangle(int a1, int h1) { a = a1; h = h1; } virtual float getRectangle() { return (a * h) / 2.0; } virtual void display() { cout << "三角形的底和高为:" << a << endl << h << endl; cout << "三角形的面积为:" << getRectangle() << endl; } };
源文件源.cpp:
#include <iostream> #include "headfile.h" using namespace std; int main() { base* p; double a = 0, a1 = 0, h1 = 0; cout << "请输入正方形的边长:" << endl; cin >> a; Square A(a); p = &A; p->display(); cout << "" << endl; cout << "请输入三角形的底和高:" << endl; cin >> a1 >> h1; Rectangle B(a1, h1); p = &B; p->display(); system("pause"); return 0; }
测试: