仍在研究继承程序,基类是 Shape 并且有三个派生类:矩形、圆形和方形(方形是从 Rectangle 派生的)。当我通过各自的构造函数设置数据值时,当我显示它们时,我得到每个派生类的数据成员的错误值我要么没有正确设置它们(我的猜测),要么我没有正确显示它们。这是一个代码片段。
class Shape
{
public:
Shape(double w = 0, double h = 0, double r = 0)
{
width = w;
height = h;
radius = r;
}
virtual double area() = 0;
void display();
protected:
double width;
double height;
double radius;
};
一个派生类:
class Rectangle : public Shape
{
public:
Rectangle(double w, double h) : Shape(w, h)
{
}
double area();
void display();
};
矩形的显示功能:
double Rectangle::area()
{
return width * height;
}
这是我的主要():
#include<iostream>
#include "ShapeClass.h"
using namespace std;
int main()
{
Rectangle r(3, 2);
Circle c(3);
Square s(3);
c.display();
s.display();
r.display();
system ("pause");
return 0;
}
完成 ShapeClass.cpp:
#include<iostream>
#include "ShapeClass.h"
using namespace std;
double Shape::area()
{
return (width * height);
}
double Rectangle::area()
{
return width * height;
}
double Circle::area()
{
return (3.14159 * radius * radius);
}
double Square::area()
{
return width * width;
}
void Square::display()
{
cout << "Side length of square: " << width << endl;
cout << "Area of square: " << this->area() << endl;
}
void Circle::display()
{
cout << "Radius of circle: " << radius << endl;
cout << "Area of circle: " << this->area() << endl;
}
void Rectangle::display()
{
cout << "Width of rectangle: " << width << endl;
cout << "Height of rectangle: " << height << endl;
cout << "Area of rectangle: " << this->area() << endl;
}