C++类的派生与继承题

2024-11-27 04:18:27
推荐回答(1个)
回答1:

自己再改改吧,这个和你要求差不多,也是一个派生与继承,基类是Rectangle, 派生类是Cube.

Cube.h
-------------------------------------------------------------------
#ifndef CUBE_H
#define CUBE_H
#include "Rectangle.h"

class Cube: public Rectangle
{
protected:
double height;
double volume;
public:
Cube() : Rectangle()
{
height= 0.0;
volume= 0.0;
}

Cube(double w, double len, double h) : Rectangle(w,len)
{
height= h;
volume= getArea() * h;
}

double getHeight() const
{
return height;
}

double getVolume() const
{
return volume;
}
};

#endif

Rectangle.h
------------------------------------------------------------
#ifndef RECTANGLE_H
#define RECTANGLE_H

class Rectangle
{
private:
double width;
double length;
public:
Rectangle()
{
width= 0.0;
length= 0.0;
}

Rectangle(double w, double len)
{
width= w;
length= len;
}

double getWidth() const
{
return width;
}

double getLength() const
{
return length;
}

double getArea() const
{
return width * length;
}
};

#endif

main.cpp (主函数)
---------------------------------------------------------------------
#include
#include "Cube.h"
using namespace std;

int main()
{
double cubeWidth;
double cubeHeight;
double cubeLength;

cout<< "Enter the dimension of a Cube: \n";
cout<< "Width: ";
cin>> cubeWidth;

cout<< "Length: ";
cin>> cubeLength;

cout<< "Height: ";
cin>> cubeHeight;

Cube myCube(cubeWidth, cubeLength, cubeHeight);

cout<< "Here are the Cube's properties: \n";
cout<< "Width: "< cout<< "Length: "< cout<< "Height: "< cout<< "Base area: "< cout<< "Volume: "<
return 0;
}