qwdqwefwf 2023-03-02 21:41 采纳率: 100%
浏览 26
已结题

关于C++析构函数的自动调用的问题

请问这个程序中c_1,c_3的析构函数为什么没有调用呀

#include <iostream>

using namespace std;
class CCountry{
    private:
        char *m_name;
        double m_area;
    public:
        CCountry();
        CCountry(char*,double);
    //析构函数
        ~CCountry();

        CCountry(const CCountry &obj);
        void Print();
        int CompareArea(CCountry);
};

CCountry::CCountry()
{
    cout<<"无参构造函数"<<endl;
}

CCountry::CCountry(char* name,double area)
{   //char*不能直接转string
    string str=name;
    cout<<str<<"的含参构造函数"<<endl;
    m_area=area;
    m_name=name;
}

CCountry::~CCountry()
{   
    string str=m_name;
    cout<<str<<"的析构函数"<<endl;
}

CCountry::CCountry(const CCountry &obj)
{
    m_area=obj.m_area;
    m_name=obj.m_name;
    string str=m_name;
    cout<<str<<"的拷贝构造函数"<<endl;
}
void CCountry::Print()
{
    cout<<m_name<<"  "<<m_area<<endl;
}

//该对象比传入对象大,返回1
int CCountry::CompareArea(CCountry c)
{
    if(m_area>c.m_area)
       {return 1;} 
    if(m_area<c.m_area)
        {return 0;}
    if(m_area==c.m_area)
        {return 2;}
    return -1;
}

int main()
{   cout<<"dsqw"<<endl;
    CCountry c_1((char*)"coutry1",20.0);
    CCountry *c_2 =new CCountry((char*)"country2",30);
    CCountry c_3(c_1);
    CCountry c_4((char*)"country4",40);
    c_1.Print();
    c_2 ->Print();
    c_3.Print();
    c_4.Print();
    cout<<c_1.CompareArea(c_4)<<endl;
    delete(c_2);
    system("pause");
}

img

  • 写回答

1条回答 默认 最新

  • 真相重于对错 2023-03-03 10:29
    关注

    调用了,只是你没看到
    你把maiin函数里面的代码放到一个函数里,然后main函数调用那个函数,自然就会看到

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月11日
  • 已采纳回答 3月3日
  • 创建了问题 3月2日

悬赏问题

  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥50 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图