定义类的头文件
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;
}