标题:[求教]析构函数和构造函数还是有些不懂
取消只看楼主
q6866223
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2014-2-19
结帖率:0
已结贴  问题点数:10 回复次数:0 
[求教]析构函数和构造函数还是有些不懂
才学C++ 没几天,不太明白构造函数和析构函数,高手帮看一下下面的代码,解释下为什么会有这样的输出。
程序代码:
#include <iostream>
#include <vector>
using namespace std;

struct Exmp1{
    Exmp1()
    {
        cout<<"Exmp1()"<<endl;  //默认构造函数 
    }
    Exmp1(const Exmp1&)
    {
        cout<<"Exmp1(const Exmp1&)"<<endl;  //复制构造函数 
    }
    Exmp1&operator=(const Exmp1 &rhe)
    {
        cout<<"operator=(const Exmp1&)"<<endl;  //赋值操作符
        return *this; 
    }
    //析构函数
    ~Exmp1()
    {
        cout<<"~Exmp1()"<<endl;
    } 
};
void func1(Exmp1 obj){}    //形参为Exmp1对象的引用 
void func2(Exmp1&obj){}  //形参为Exmp1对象的引用
Exmp1 func3(){
    Exmp1 obj;
    return obj;
} 
int main()
{
    Exmp1 eobj;
    func1(eobj);
    func2(eobj);
    eobj = func3();
    Exmp1 *p=new Exmp1;
    vector<Exmp1>evec(3);
    delete p;
    return 0;
}


输出:
Exmp1()
Exmp1(const Exmp1&)
~Exmp1()
Exmp1()
operator=(const Exmp1&)
~Exmp1()
Exmp1()
Exmp1()
Exmp1(const Exmp1&)
Exmp1(const Exmp1&)
Exmp1(const Exmp1&)
~Exmp1()
~Exmp1()
~Exmp1()
~Exmp1()
~Exmp1()
~Exmp1()

--------------------------------
Process exited with return value 0
Press any key to continue . . .
搜索更多相关主题的帖子: color 
2015-06-01 17:12



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




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

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