写一些复杂的cpp代码
时间: 2023-02-09 07:41:50 浏览: 64
下面是一个使用了多重继承、虚函数和模板的 C++ 代码示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 定义基类 Shape
class Shape {
public:
Shape(const string& name) : m_name(name) {}
virtual ~Shape() {}
virtual double area() const = 0;
virtual double perimeter() const = 0;
string name() const { return m_name; }
private:
string m_name;
};
// 定义派生类 Circle,继承自 Shape
class Circle : public Shape {
public:
Circle(double radius) : Shape("Circle"), m_radius(radius) {}
double area() const { return 3.14 * m_radius * m_radius; }
double perimeter() const { return 2 * 3.14 * m_radius; }
private:
double m_radius;
};
// 定义派生类 Rectangle,继承自 Shape
class Rectangle : public Shape {
public:
Rectangle(double length, double width)
: Shape("Rectangle"), m_length(length), m_width(width) {}
double area() const { return m_length * m_width; }
double perimeter() const { return 2 * (m_length + m_width); }
private:
double m_length;
double m_width;
};
// 定义基类 GraphicObject
class GraphicObject {
public:
GraphicObject(const string& name) : m_name(name) {}
string name() const { return m_name; }
void print() const {
cout << "GraphicObject: " << m_name << endl;
for (const auto& s : m_shapes) {
cout << " " << s->name() << ": " << s->area() << endl;
}
}
protected:
void add(Shape* shape) { m_shapes.push_back(shape); }
private:
string m_name;
vector<Shape*> m_shapes;
};
// 定义派生类 CircleGraphic,继承自 GraphicObject 和 Circle
class CircleGraphic : public GraphicObject, public Circle {
public:
CircleGraphic(double radius) : GraphicObject("CircleGraphic"), Circle(radius) {
add(this);
}
};
// 定义派生类 RectangleGraphic,继承自 GraphicObject 和 Rectangle
class RectangleGraphic : public GraphicObject, public Rectangle {
public:
RectangleGraphic(double length, double width)
: GraphicObject("RectangleGraphic"),
Rectangle(length,