C++ 类和对象——构造函数

构造函数和析构函数

#include<iostream>
using namespace std;
class example{
public:
	example(){
		cout << "调用构造函数" << endl; 
	}
	~example(){
		cout << "调用析构函数" << endl;
	}
}; 

void test(){
	example test;
} 
int main(){
	test();
	return 0;
}

运行结果:
调用构造函数
调用析构函数
代码模拟更清晰看到:在创建一个test对象的时候首先运行的是构造函数,在函数test结束以后系统回收时运行析构函数

构造函数的分类和调用

分类方式:有参构造/无参构造;普通构造/拷贝构造

调用方式:括号法,显示法,隐式转换法

class example{
public:

	//无参构造 
	example(){
		cout << "调用无参构造函数" << endl; 
	}
	
	//有参构造 
	example(int a){
		age = a;
		cout << "调用有参构造函数" << endl; 
	}

	//拷贝构造函数
	example(const example &p){
		age  = p.age;
		cout << "调用拷贝构造函数" << endl;
	} 

	~example(){
		cout << "调用析构函数" << endl;
	}

	int age;
}; 

void test(){
	//括号法 
	example test01; //默认构造函数调用 ,该方式不用括号。有括号会被编译器默认函数声明 
	example test02(10);//有参数,调用有参函数构造
	example test03(test02);//传入类,调用拷贝函数构造
	cout << "test02的年龄:" << test02.age<< endl;
	cout << "test03的年龄:" << test03.age<< endl;
	
	//显示法
	example test01; //默认构造函数调用 ,该方式不用括号。有括号会被编译器默认函数声明 
	example test02 = example(10);//有参数,调用有参函数构造
	example test03 = example(test02);//传入类,调用拷贝函数构造
	cout << "test02的年龄:" << test02.age<< endl;
	cout << "test03的年龄:" << test03.age<< endl;
	example(10); //匿名对象,当场创建,当场回收
				 //拷贝构造函数无法初始化匿名对象。  编译器内 example(test03)等价于example test03 重定义问题
	
	//隐式转换法
	//进一步省略函数,直接用参可以定义 
	example test04 = 10;
	example test05 = test02;
} 
int main(){
	test();
	return 0;
}
posted @ 2026-05-19 19:23  www6526  阅读(5)  评论(0)    收藏  举报