注册 登录
编程论坛 C++教室

[求教]析构函数和构造函数还是有些不懂

q6866223 发布于 2015-06-01 17:12, 819 次点击
才学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 . . .
10 回复
#2
yangfrancis2015-06-01 22:22
没看懂为什么会输出复制构造函数的内容,期待能人解答。
#3
Qszszz2015-06-01 22:33
论坛如何发帖子啊
#4
rjsp2015-06-02 08:22
哪一句不懂?
将不懂的那句留下,将懂的删除。
#5
诸葛欧阳2015-06-02 11:09
调用func1函数时形参就是调用拷贝构造函数复制eobj的
#6
yangfrancis2015-06-02 12:16
回复 3楼 Qszszz
点“发表文章”
#7
yangfrancis2015-06-02 12:19
回复 5楼 诸葛欧阳
说起来,传参时复制一个对象副本和对象自己执行复制构造函数是一回事么。没研究过这个。
#8
诸葛欧阳2015-06-02 14:36
程序代码:
#include <iostream>
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对象的引用
int main()
{
    Exmp1 eobj;
    func1(eobj);
    return 0;
}

结果:Exmp1()
Exmp1(const Exmp1&)
~Exmp1()
Exmp1()
#9
诸葛欧阳2015-06-02 14:37
回复 7楼 yangfrancis
通过楼上结果可以说明这个问题
#10
纸T02015-06-05 17:33
比如

void func3(){
    int x;
    int y;
}


func3()就是一个函数。函数体内是
 int x;
 int y;

x,y各占了四个字节。如果func3()老占着内存怎么办?

所以析构函数就是针对这样的函数的。
~func3()
{
   
}

~func3()


 }是析构函数,函数体内通常为空。这样func3()这个函数所占的空间就被释放了,或者说func3()所占的内存被收回了。
#11
诸葛欧阳2015-06-05 18:22
回复 10楼 纸T0
对于非成员函数,析构函数不会去处理吧
1