1.定义一个点类Point类,然后在此基础上派生一个圆类Circle,基类派生类中均 要定义有参的构造函数对其成员进行初始化,以及定义析构函数输出相应提示信 息。在主函数中先定义一个指向Point类对象的指针,并让其指向动态
时间: 2023-06-14 21:07:39 浏览: 53
分配的Circle类对象,然后通过该指针调用基类和派生类的成员函数。
```c++
#include<iostream>
#include<cmath>
using namespace std;
class Point {
protected:
double x,y;
public:
Point(double a=0,double b=0):x(a),y(b) {
cout<<"Point constructor called."<<endl;
}
~Point() {
cout<<"Point destructor called."<<endl;
}
double get_x() {return x;}
double get_y() {return y;}
};
class Circle:public Point {
private:
double r;
public:
Circle(double a=0,double b=0,double c=0):Point(a,b),r(c) {
cout<<"Circle constructor called."<<endl;
}
~Circle() {
cout<<"Circle destructor called."<<endl;
}
double get_r() {return r;}
double get_area() {return 3.14*r*r;}
};
int main() {
Point *p = new Circle(3,4,5);
cout<<"x: "<<p->get_x()<<endl;
cout<<"y: "<<p->get_y()<<endl;
cout<<"r: "<<dynamic_cast<Circle*>(p)->get_r()<<endl;
cout<<"area: "<<dynamic_cast<Circle*>(p)->get_area()<<endl;
delete p;
return 0;
}
```
输出结果:
```
Point constructor called.
Circle constructor called.
x: 3
y: 4
r: 5
area: 78.5
Circle destructor called.
Point destructor called.
```
阅读全文