题目要求和程序代码如下:
⑴ 定义一个基类Shape,由Shape派生出Circle和Rectangle类,用来实现计算各种不同类型图形面积的功能。
⑵ 要求
将类族的定义部分保存为头文件shape.h,将类族的成员函数的定义保存为源文件shape.cpp,最后建立一个主程序文件,命名为sy13_1.cpp。
⑶ 程序代码
//sy13_1:shape.h
class Shape{
//基类Shape的定义
public:
double getArea()const;
void print()const;
};
//Shape类定义结束
class Circle: public Shape {
public:
Circle ( int = 0, int = 0, double = 0.0 );
double getArea() const;
// 返回面积
void print() const;
// 输出Circle 类对象
private:
int x,y;
// 圆心坐标
double radius;
// 圆半径
};
// 派生类Circle定义结束
class Rectangle : public Shape {
public:
Rectangle( int = 0, int = 0);
// 构造函数
double getArea() const;
// 返回面积
void print() const;
// 输出Rectangle类对象
private:
int a,b;
// 矩形的长和宽
};
// 派生类Rectangle定义结束
// sy13_1:shape.cpp
#include
using namespace std;
#include "shape.h"
double Shape::getArea() const
{ cout<<"基类的getArea函数,面积是 ";
return 0.0;
}
// Shape类getArea函数的定义
void Shape::print() const
{ cout<<"Base class Object"<<endl;
}
//Shape类print函数定义
Circle::Circle( int xValue, int yValue, double radiusValue )
{ x=xValue;y=yValue;
radius= radiusValue ;
}
//Circle类构造函数
double Circle::getArea() const
{cout<<"Circle类的getArea函数,面积是 ";
return 3.14159 * radius * radius;
}
//Circle类getArea函数定义
void Circle::print() const
{cout << "center is ";
cout<<"x="<<x<<" y="<<y;
cout << "; radius is " << radius<<endl;
}
//Circle类print函数定义
Rectangle::Rectangle( int aValue, int bValue )
{ a=aValue;b=bValue;
}
// Rectangle类构造函数
double Rectangle::getArea() const
{cout<<"Rectangle类的getArea函数,面积是 ";
return a * b;
}
// Rectangle类getArea函数定义
void Rectangle::print() const
{cout << "hight is "<<a;
cout<<"width is"<
using std::cout;
using std::endl;
#include "shape.h"
// 包含头文件
void main()
{Circle circle ( 22, 8, 3.5 );
// 创建Circle类对象
Rectangle rectangle (10, 10 );
// 创建Rectangle类对象
cout << "调用的是 ";
cout<<circle.getArea() << endl;
// 静态联编
cout << "调用的是";
cout<<rectangle.getArea() << endl;
// 静态联编
}
可是运行的时候出现了:
fatal error C1083: Cannot open include file: 'shape.h': No such file or directory
怎么办?
|