构造函数 复制构造函数 类型转换构造函数 析构函数

来源:互联网 发布:金字塔软件论坛 编辑:程序博客网 时间:2024/06/05 02:40

关于题目中几个构造函数和析构函数的几段程序,主要在于知道什么时候调用各个函数。

程序一:

#include <iostream>using namespace std;class Complex{public:double real;double imag;Complex(double r, double i) {real = r;imag = i;cout << "Construtor 1 called!" << endl;}//类型转换构造函数Complex(int r){real = r;imag = 0;cout << "Construtor 2 called!" << endl;}//复制构造函数Complex(Complex &c){real = c.real;imag = c.imag;cout << "Construtor 3 called!" << endl;}//析构函数~Complex(){cout << "Desturctor called!" << endl;}};void Func(Complex c){}Complex Func2(){Complex c(3,4);return c;}int main(){Complex c1(9, 7);//1Complex c2(c1);//3Complex c3 = c1;//3Complex c4 = 9;// 2 c1 = 5;//2 dFunc(c1);//3 dc2 = Func2(); //1 dcout << Func2().real << endl;//1 dcout << c1.real << "+" << c1.imag << "i" << endl;return 0;// d d d d}

程序二:

/*会调用几次析构函数?3次!*/#include <iostream>using namespace std;class A{public:int num;A(){}~A(){cout << "Destructor!" << endl;}};int main() {A * p = new A[2];A * p2 = new A;A a;delete [] p;}

程序三:


#include<iostream>using namespace std;class Demo{int id;public:Demo(int i){id = i;cout << "id=" << id << "constructor" << endl;}~Demo(){cout << "id=" << id << "destructor" << 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;}


0 0