C++题目,急,希望能有完整解答

来源:百度知道 编辑:UC知道 时间:2024/05/28 20:05:37
2.按要求对以下程序做修改。
#include <iostream>
using namespace std;
class Shape
{public:
Shape(){}
~Shape()
{cout<<"executing Shape destructor"<<endl;}
};
int main()
{Shape *p=new Circle;
delete p;
return 0;
} class Circle:public Shape
{public:
Circle(){}
~Circle()
{cout<<"executing Circle destructor"<<endl;}
private:
int radus;
};

(1)把构造函数修改为带参数的函数,在建立对象时初始化。
(2)不将析构函数声明为虚函数,在main函数中另设一个指向Circle类对象的指针变量,使它指向grad1,运行程序,分析结果。
(3)将析构函数声明为虚函数,运行程序,分析结果。

我之前回答别人的:

#include <iostream>
using namespace std;
class Shape
{
public:
Shape(){}
~Shape()
{
cout<<"executing Shape destructor"<<endl;
}
};

class Circle:public Shape
{
public:
Circle(){}
/////////////////////////////////
Circle(Circle &c):radus(c.radus)
{
}
Circle(int c):radus(c)
{
}
/////////////////////////////////
~Circle()
{
cout<<"executing Circle destructor"<<endl;
}
private:
int radus;
};

int main()
{
Shape *p=new Circle(1);
delete p;
return 0;
}

其实加不加virtual 就决定了是否会调用子类的析构函数,如果不加virtual不会建立虚函数表,也就是找不到子类的析构函数的入口地址,没有办法调用

仅此而已