试着写出所能想象的所有形状,生成一个形状层次类结构,生成的类结构以shape作为基类,并由此生出Twodimshape类和Threedimshape类,他们的派生类是不同形状类,定义层次结构中每一个类并用main函数测试。用c++写
时间: 2024-12-06 17:20:10 浏览: 9
在C++中,我们可以创建一个简单的形状层次类结构,包括基础形状、二维形状和三维形状。首先,我们从`Shape`基类开始,然后创建派生类如`Circle`, `Square`等属于二维形状,以及`Cube`, `Sphere`等属于三维形状。以下是一个简化的示例:
```cpp
#include <iostream>
#include <string>
// 基础形状
class Shape {
public:
virtual ~Shape() {}
virtual std::string getDimension() const = 0; // 获取形状维度
virtual void display() const = 0; // 展示形状信息
};
// 二维形状
class Twodimshape : public Shape {
protected:
std::string shapeType;
public:
Twodimshape(const std::string& type) : shapeType(type) {}
std::string getDimension() const override { return "Two-dimensional"; }
virtual void display() const override {
std::cout << "This is a " << shapeType << " shape." << std::endl;
}
};
// 具体的二维形状例子,比如圆形和正方形
class Circle : public Twodimshape {
public:
Circle(double radius) : Twodimshape("Circle"), radius(radius) {}
double radius;
void display() const override {
Twodimshape::display();
std::cout << "Radius: " << radius << std::endl;
}
};
class Square : public Twodimshape {
public:
Square(int side) : Twodimshape("Square"), side(side) {}
int side;
void display() const override {
Twodimshape::display();
std::cout << "Side length: " << side << std::endl;
}
};
// 三维形状
class Threedimshape : public Shape {
protected:
std::string shapeType;
public:
Threedimshape(const std::string& type) : shapeType(type) {}
std::string getDimension() const override { return "Three-dimensional"; }
virtual void display() const override {
std::cout << "This is a " << shapeType << " shape." << std::endl;
}
};
// 具体的三维形状例子,比如立方体和球体
class Cube : public Threedimshape {
public:
Cube(double edgeLength) : Threedimshape("Cube"), edgeLength(edgeLength) {}
double edgeLength;
void display() const override {
Threedimshape::display();
std::cout << "Edge length: " << edgeLength << std::endl;
}
};
class Sphere : public Threedimshape {
public:
Sphere(double radius) : Threedimshape("Sphere"), radius(radius) {}
double radius;
void display() const override {
Threedimshape::display();
std::cout << "Radius: " << radius << std::endl;
}
};
int main() {
Circle circle(5);
square Square(4);
Cube cube(3);
Sphere sphere(2);
circle.display();
square.display();
cube.display();
sphere.display();
return 0;
}
```
在这个例子中,`main()`函数中展示了每个形状的实例,并通过`display()`方法展示其信息。
阅读全文