标题: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
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册: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



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-479039-1-1.html




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

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