[求教]析构函数和构造函数还是有些不懂
才学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 . . .