#include<iostream> using namespace std; class CExample { private: int a; int n; public: //构造函数 CExample(int b) { a=b; printf("constructor1 is called\n"); } CExample(int c, int d) { a=c; printf("constructor2 is called\n"); } CExample(int c, int d, int e) { a=c; printf("constructor2 is called\n"); } //拷贝构造函数 CExample(const CExample & c) { a=c.a; printf("copy constructor is called\n"); } //析构函数 ~CExample() { cout<<"destructor is called\n"; } void show() { cout<<a<<endl; } }; int main() { CExample A(100); CExample B(12,24); A.show(); B.show(); return 0; //A.Show(); //CExample B=A; //B.Show(); }
运行结果是:
constructor1 is called constructor2 is called 100 12 destructor is called destructor is called
attention:
CExample A(100);
CExample B(12,24)
//生成对象A 并用100初始化A。100就自动调用对象中的构造函数
//如果是CExample A(100,200) 那上面必须有一个构造函数的参数是两个,如果是的话,这一过程即CExample A(100); CExample A(100,200)
//执行结束后,析构函数会执行两次
//构造函数不能有相同的参数,会提示重载出错,n个构造函数执行,析构函数就会执行N次。
//可以有多个构造函数,但是只能有一个析构函数
原文:https://www.cnblogs.com/kuangbendesaozhu/p/14447278.html