关于题目中几个构造函数和析构函数的几段程序,主要在于知道什么时候调用各个函数。
程序一:
#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); //1
Complex c2(c1); //3
Complex c3 = c1; //3
Complex c4 = 9; // 2
c1 = 5; //2 d
Func(c1); //3 d
c2 = Func2(); //1 d
cout << Func2().real << endl; //1 d
cout << 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;
}