#include
using namespace std;
class shape //虚基类
{public:
double x;
double y;
shape()
{double a,b;
cin>>a>>b;
x=a;
y=b;} //构造函数
virtual void area()=0;
virtual void print()=0;
};
class triangle:public shape //三角形
{
double a;
public:
void area() //三角形面积
{
a=0.5*x*y;
}
void print() //三角形输出函数
{
cout<<"TriangleArea="<<a<<endl;
}
};
class rectangle:public shape //矩形
{
double a;
public:void area()
{
a=x*y;
}
void print()
{
cout<<"RectangleArea="< }
};
class circle:public shape //圆
{
double a;
public:
void area()
{
a=3.14*x*x;
}
void print()
{
cout }
};
int main()
{
shape *p;
triangle a;
rectangle b;
circle c;
p=&a;
p->area();
p->print();
p=&b;
p->area();p->print();
p=&c;
p->area();p->print();
return 0;
}
利用C++的多态性,设计一快递运费计算软件。 货物由北京可通过快递公司运往天津、上海、太原、广州、昆明、新疆六个城市,分别用1、2、3、4、5、6作为它们编号。运送货物的重量分为1、2、3公斤。快递公司有四家:E通宝、顺风、EMS和圆通,编号为1、2、3、4。不同城市、不同重量、不同的快递公司所费用由表1给出。当输入快递公司编号、城市编号和货物重量时,屏幕输出货物运送快递公司名称、到达的城市及费用。编程要求如下:
1.定义一基类为快递公司,类中定义“城市编号”、货物个数、重量等成员,成员函数有基本成员输出函数及两个纯虚函数:求运输费用函数和输出信息函数。
2.分别定义各快递公司的派生类,在类中参照表中提供的数据,根据自己的实际,编写各自的运输费用函数和输出信息函数。
3.用实例测试。在主函数中定义一基类的指针数组,使这些指针分别指向不同的快递公司。
问题如上,不知道为啥运行出来输入x和y之后无反应,是不是构造函数初始化的方法不对??
不是没有反应,而是你的输入少了。
shape *p;
triangle a;
rectangle b;
circle c;
triangle a;
由于triangle类继承了shape类,当构造triangle的时候,先构造shape,此时需要输入两个值
rectangle b;
由于rectangle类也继承了shape类,当构造rectangle的时候,先构造shape,此时又需要输入两个值
circle c;
由于circle类也继承了shape类,当构造circle的时候,先构造shape,此时又又需要输入两个值
因此图如下
#include <iostream>
using namespace std;
class shape //虚基类
{
public:
double x;
double y;
shape(int x_, int y_) : x(x_), y(y_)
{
} //构造函数
virtual void area() = 0;
virtual void print() = 0;
};
class triangle : public shape //三角形
{
double a;
using shape::x;
using shape::y;
public:
triangle(int x_, int y_) : shape(x_, y_) { }
void area() //三角形面积
{
a = 0.5*x*y;
}
void print() //三角形输出函数
{
cout << "TriangleArea=" << a << endl;
}
};
class rectangle :public shape //矩形
{
double a;
using shape::x;
using shape::y;
public:
rectangle(int x_, int y_) : shape(x_, y_) { }
void area()
{
a = x*y;
}
void print()
{
cout << "RectangleArea=" << a << endl;
}
};
class circle :public shape //圆
{
double a;
using shape::x;
using shape::y;
public:
circle(int x_, int y_) : shape(x_, y_) { }
void area()
{
a = 3.14*x*x;
}
void print()
{
cout << "circle=" << a << endl;
}
};
int main()
{
shape *p;
int x, y;
cin >> x >> y;
triangle a(x, y);
rectangle b(x, y);
circle c(x, y);
p = &a;
p->area();
p->print();
p = &b;
p->area(); p->print();
p = &c;
p->area(); p->print();
return 0;
}