构造函数 复制构造函数 类型转换构造函数 析构函数
2015-03-23 15:38
260 查看
关于题目中几个构造函数和析构函数的几段程序,主要在于知道什么时候调用各个函数。
程序一:
程序二:
程序三:
程序一:
#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; }
相关文章推荐
- 构造函数、复制构造函数、类型转换构造函数、析构函数
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容 【转】 参考度4.6星
- 写一个类的构造函数、复制构造函数、析构函数、赋值函数
- 构造函数、复制构造函数、析构函数混合使用总结
- c++类临时对象、复制构造函数、析构函数 VS2017 与gcc 编译器对比
- 析构函数、复制构造函数,operator=以及深拷贝浅拷贝问题
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容
- (总结)C++的构造函数(初始化列表,缺省/复制和带默认参数的构造函数)和析构函数详解
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容
- C++语法基础--复制控制--复制构造函数 ,赋值操作符 ,析构函数
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容 【转】 参考度4.6星
- c++ 构造函数,复制构造函数,赋值构造函数,析构函数调用时机
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容
- 关于默认构造函数、复制构造函数、析构函数、赋值操作的各种测试探索
- c++ 构造函数,析构函数,复制构造函数
- 默认构造函数,复制构造函数,赋值操作符函数,析构函数的调用。
- 类中的构造函数,析构函数,复制构造函数,赋值函数
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容