#pragma once
//Shape类为抽象类
const double PI = 3.14;
class Shape
{
public:
//Shape();
//~Shape();
virtual double GetArea()=0; //纯虚函数,计算面积
virtual double GetPerimeter() = 0; //纯虚函数,计算周长
};
#pragma once
#include "Shape.h"
class Circle : public Shape //继承自Shape类
{
public:
Circle(int nR);
~Circle();
double GetArea(); //计算面积
double GetPerimeter(); //计算周长
private:
double m_nR; //半径
};
#include "stdafx.h"
#include "Circle.h"
Circle::Circle(int nR)
{
m_nR = nR;
}
Circle::~Circle()
{
}
double Circle::GetArea() //计算面积
{
return PI * m_nR * m_nR;
}
double Circle::GetPerimeter() //计算周长
{
return 2 * PI * m_nR;
}
#pragma once
#include "Shape.h"
class Rectangle :public Shape//类的继承
{
public:
Rectangle(double nLength, double nWidth);
~Rectangle();
double GetArea(); //计算面积
double GetPerimeter(); //计算周长
private:
double m_nLength, m_nWidth; //长,宽
};
#include "stdafx.h"
#include "Rectangle.h"
Rectangle::Rectangle(double nLength, double nWidth)
{
m_nLength = nLength;
m_nWidth = nWidth;
}
Rectangle::~Rectangle()
{
}
double Rectangle::GetArea() //计算面积,重定义
{
return m_nLength*m_nWidth;
}
double Rectangle::GetPerimeter() //计算周长,重定义
{
return 2 * (m_nLength + m_nWidth);
}
// ClassExampleVirtual2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Shape.h"
#include"Circle.h"
#include "Rectangle.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int r = 3; //圆的半径
int a = 8, b = 5; //矩形的长和宽
Circle circle(r); //
Rectangle rectangle(8, 5);
cout << "圆的面积为:" << circle.GetArea() << endl
<< "圆的周长为:" << circle.GetPerimeter() << endl
<< "矩形的面积为" << rectangle.GetArea() << endl
<< "矩形的周长为:" << rectangle.GetPerimeter() << endl;
getchar();
return 0;
}
运行结果:
?
|