c++构造函数的分类和调用

(1)  构造函数的分类

       1) 无参数构造函数  2) 带参数构造函数   3)拷贝构造函数  4)默认构造函数,如果c++编译器没有提供构造函数

       

Test2()  //无参数构造函数
{
	m_a = 0;
	m_b = 0;
	cout << "无参数构造函数" << endl;
}

Test2(int a)
{
	m_a = a;
	m_b = 0;
	cout << "一个参数构造函数" << endl;
}

Test2(int a, int b) //有参数构造函数   //3种方法
{
	m_a = a;
	m_b = b;
	cout << "两个参数数构造函数" << endl;
}

//赋值构造函数 (copy构造函数) //
Test2(const Test2& obj)
{
	cout << "拷贝构造函数 " << endl;
}

(2)  调用方法(具体看注释):

       

#include <iostream>
using namespace std;

class Test2
{
public:
	Test2()  //无参数构造函数
	{
		m_a = 0;
		m_b = 0;
		cout << "无参数构造函数" << endl;
	}

	Test2(int a)
	{
		m_a = a;
		m_b = 0;
		cout << "一个参数构造函数" << endl;
	}

	Test2(int a, int b) //有参数构造函数   //3种方法
	{
		m_a = a;
		m_b = b;
		cout << "两个参数数构造函数" << endl;
	}

	//赋值构造函数 (copy构造函数) //
	Test2(const Test2& obj)
	{
		cout << "拷贝构造函数 " << endl;
	}

public:
	void printT()
	{
		cout << m_b << endl;
	}
private:
	int m_a;
	int m_b;
};

void main21()
{
	Test2 t1;  //调用无参数构造函数,输出“无参数构造函数”
	cout << "hello..." << endl;
	system("pause");
	return;
}

//调用 调用有参数构造函数 3
void main()
{
	//1括号法 
	Test2 t1(1, 2);  //调用参数构造函数  c++编译器自动的调用构造函数,输出“两个参数构造函数”
	
	// 2 =号法
	Test2 t2 = (3, 4, 5, 6, 7); //输出"一个参数构造函数", 这是逗号表达式,只取最后一个值7,7就是表达式的值,相当于调用一个参数的函数,= c++对等号符 功能增强  c++编译器自动的调用构造函数

	Test2 t3 = 5;   //输出"一个参数构造函数"

	//3 直接调用构造函数  手动的调用构造函数
	Test2 t4 = Test2(3, 4);   //输出"两个参数构造函数"     //匿名对象 (匿名对象的去和留) 抛砖 ....//t4对象的初始化
	//
	t1 = t4;  //把t4 copy给 t1  //赋值操作 
	//对象的初始化 和 对象的赋值 是两个不同的概念 


	t1.printT();   //输出4
	cout << "hello..." << endl;
	system("pause");
	return;
}

     

发布了200 篇原创文章 · 获赞 77 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/tianguiyuyu/article/details/102984041