为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的 不能析构coordinate 他析构了circle~


#include<bits/stdc++.h>

using namespace std;

class shape{

public:

shape(){

cout<<"shape"<<endl;

}

virtual ~shape(){

cout<<"~shape"<<endl;

}

virtual double calc(){

cout<<"calc"<<endl;

return 0;

}

};

class  coordinate{

public:

coordinate(int x,int y){

cout<<"coordiante"<<endl;

        m_x=x,m_y=y; 

}

~coordinate(){

cout<<"~coordiante"<<endl;

}

    protected:

    int m_x,m_y;

}; 

class circle:public shape

{

public:

circle(double r){

m_r=r;

cout<<"circle"<<endl;

coordinate *m_p=new coordinate(3,5);

}

virtual ~circle(){

cout<<"~circle"<<endl;

delete m_p;

m_p=NULL;

}

double calc(){

cout<<"circle->calc"<<endl;

cout<<m_r*m_r*3.14<<endl;

return 0;

}

protected:

double m_r;

coordinate *m_p;

};

int main(){

circle *p=new circle(3);

delete p;

p=NULL;

return 0;


正在回答

1 回答

circle的类定义内,构造函数内coordinate *m_p=new coordinate(3,5);与数据成员中coordinate *m_p;矛盾,

不妨改为如下,这样随着对象的解构,自动进行coordinate的析构函数

class circle:public shape

{

public:

circle(double r):m_p(3,5)

{

m_r=r;

cout<<"circle"<<endl;

}

virtual ~circle(){

cout<<"~circle"<<endl;

}

protected:

double m_r;

coordinate m_p;

};


0 回复 有任何疑惑可以回复我~
#1

qq_慕姐2217196 提问者

你这样说也有点道理 我试了一下,按你那样直接报错了 我的疑惑 是我的代码 circle的析构函数他都执行了输出~circle的指令 却木有执行析构coordinate这个堆的指令
2020-03-07 回复 有任何疑惑可以回复我~
#2

qq_慕姐2217196 提问者

我知道了,应该 是你说的问题,堆实例化的时候前面不能加coordinate *,应该 m_p=new coordinate(3,4);就行了,那个circle 的析构函数是读的是protected里面的m_p
2020-03-07 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之多态篇
  • 参与学习       66254    人
  • 解答问题       314    个

本教程将带领大家体会面向对象三大特性中的多态特性

进入课程

为什么我的 不能析构coordinate 他析构了circle~

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信