c++中怎么用点作为基类,派生类怎么样定义矩形和圆
时间: 2024-05-02 16:20:41 浏览: 100
回答:关于类的继承和派生,可以通过在基类后面添加冒号和继承方式来定义派生类。使用点作为基类可以通过以下方式实现:
```
class Point {
protected:
int x;
int y;
public:
Point() {}
Point(int xx, int yy) : x(xx), y(yy) {}
// getter and setter methods
int getX() const {
return x;
}
void setX(int xx) {
x = xx;
}
int getY() const {
return y;
}
void setY(int yy) {
y = yy;
}
};
class Shape : public Point {
public:
Shape() {}
Shape(int xx, int yy) : Point(xx, yy) {}
};
class Rectangle : public Shape {
private:
int width;
int height;
public:
Rectangle() {}
Rectangle(int xx, int yy, int w, int h) : Shape(xx, yy), width(w), height(h) {}
// getter and setter methods
int getWidth() const {
return width;
}
void setWidth(int w) {
width = w;
}
int getHeight() const {
return height;
}
void setHeight(int h) {
height = h;
}
};
class Circle : public Shape {
private:
int radius;
public:
Circle() {}
Circle(int xx, int yy, int r) : Shape(xx, yy), radius(r) {}
// getter and setter methods
int getRadius() const {
return radius;
}
void setRadius(int r) {
radius = r;
}
};
```
以上是一个简单的继承关系图,基类为Point,形状类Shape继承自Point,然后圆形和矩形分别继承自Shape类来实现。
阅读全文