| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1290 人关注过本帖
标题:C++一个析构函数的疑惑?
只看楼主 加入收藏
hcs_xiaohan
Rank: 2
等 级:论坛游民
帖 子:40
专家分:23
注 册:2016-7-4
结帖率:91.67%
收藏
已结贴  问题点数:13 回复次数:1 
C++一个析构函数的疑惑?
源代码如下:

#include <iostream>

using namespace std;

class Demo {
    int id;
public:
    Demo(int i)
    {
        id = i;
        cout << "id = " << id << " Constructed" << endl;
    }
    ~Demo()
    {
        cout << "id = " << id << " Destructed" << endl;
    }
};

Demo d1(1);
void Func() {
    static Demo d2(2);
    Demo d3(3);
    cout << "Func" << endl;
}
int main() {
    Demo d4(4);
    d4 = 6;
    cout << "main" << endl;
    { Demo d5(5); }
    Func();
    cout << "main ends" << endl;
    return 0;
}


输出如下:


id=1 Constructed
id=4 Constructed
id=6 Constructed
id=6 Destructed
main
id=5 Constructed
id=5 Destructed
id=2 Constructed
id=3 Constructed
Func
id=3 Destructed
main ends
id=6 Destructed
id=2 Destructed
id=1 Destructed

我不明白为什么出现了三次 id=6,请各位指导一下。
搜索更多相关主题的帖子: C++ 析构函数 int cout main 
2017-06-28 23:43
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9031
专家分:54061
注 册:2011-1-18
收藏
得分:13 
我帮你去掉和问题屁关系都没有的代码,并按照正常人风格修改了一下
程序代码:
#include <iostream>

class Demo
{
public:
    Demo( int id ) : id_(id)
    {
        std::cout << "Address=" << this << " id = " << id_ << " Constructed" << std::endl;
    }
    Demo( const Demo& d ) : id_(d.id_)
    {
        std::cout << "Address=" << this << " id = " << id_ << " Copy Constructed" << std::endl;
    }
    Demo& operator=( const Demo& d )
    {
        id_ = d.id_;
        std::cout << "Address=" << this << "<--" << &d << " id = " << id_ << " Assign Operator" << std::endl;
        return *this;
    }
    ~Demo()
    {
        std::cout << "Address=" << this << " id = " << id_ << " Destructed" << std::endl;
    }

protected:
    int id_;
};

using namespace std;

int main( void )
{
    Demo d4(4);
    d4 = 6;

    return 0;
}

输出
Address=0012FF6C id = 4 Constructed
Address=0012FF68 id = 6 Constructed
Address=0012FF6C<--0012FF68 id = 6 Assign Operator
Address=0012FF68 id = 6 Destructed
Address=0012FF6C id = 6 Destructed

2017-06-29 08:26
快速回复:C++一个析构函数的疑惑?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.049781 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved