C++中定義一個圖形基類,然後派生正方形、矩形等求面積和周長
阿新 • • 發佈:2019-02-13
定義類的標頭檔案
Shape.h
#ifndef __SHAPE_H #define __SHAPE_H #include <iostream> using namespace std; class Shape { public: Shape(); ~Shape(); virtual float area() = 0; virtual float perimeter() = 0; }; class Square :public Shape { private: float width; public: Square(); Square(float b); ~Square(); float area(); float perimeter(); void setWidth(float b); void print(); }; class Rect : public Shape { public: Rect(); Rect(float x, float y); ~Rect(); float area(); float perimeter(); void setWidth(float x, float y); void print(); private: float width; float height; }; #endif // !__SHAPE_H
相關函式的定義以及使用
Shape.cpp
#include "Shape.h" Shape::Shape() { cout << "基類建構函式" << endl; } Shape::~Shape() { cout << "基類解構函式" << endl; } Square::Square() { width = 0; } Square::Square(float b) { width = b; } Square::~Square(void) { cout << "正方形解構函式" << endl; } float Square::area() { return (width * width); } float Square::perimeter() { return (4 * width); } void Square::setWidth(float b) { width = b; } void Square::print() { cout << "width:" << width << endl; cout << "area:" << area() << endl; cout << "perimeter:" << perimeter() << endl; } Rect::Rect() { width = 0; height = 0; } Rect::Rect(float x, float y) { width = x; height = y; } Rect::~Rect() { cout << "矩形解構函式" << endl; } float Rect::area() { return (width * height); } float Rect::perimeter() { return (2 * (width + height)); } void Rect::setWidth(float x, float y) { width = x; height = y; } void Rect::print() { cout << "width:" << width << endl; cout << "height:" << height << endl; cout << "area:" << area() << endl; cout << "perimeter:" << perimeter() << endl; } int main() { float a = 0.0; float b = 0.0; cout << "請輸入正方形的邊長:"; cin >> a; Square S(a); S.print(); S.setWidth(5); S.print(); cout << "請輸入矩形的長:"; cin >> a; cout << "請輸入矩形的寬:"; cin >> b; Rect R(a, b); R.print(); R.setWidth(3, 4); R.print(); return 0; }