亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

為什么我的 不能析構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++遠征之多態篇
  • 參與學習       66224    人
  • 解答問題       334    個

本教程將帶領大家體會面向對象三大特性中的多態特性

進入課程

為什么我的 不能析構coordinate 他析構了circle~

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號