构造函数与析构函数(二)

头文件Test.h

#pragma once
class Test
{
public:
	Test();
	Test(int num);

	~Test();

	void Display();

	Test& operator=(const Test& other);

private:
	int num_;
};

实现文件Test.cpp

#include "Test.h"
#include <iostream>
using namespace std;

Test::Test()
{
	num_ = 0;
	cout << "Initnitialing Default" << endl;
}
Test::Test(int num)
{
	num_ = num;
	cout << "Initnitialing " << num_ << endl;
}

Test::~Test()
{
	cout << "Destroy " << num_ << endl;
}

void Test::Display()
{
	cout << "num = " << num_ << endl;
}

Test& Test::operator=(const Test& other)
{
	cout << "Test::operator=" << endl;
	//	重载==后可以写成if (*this == other)
	if (this == &other)
		return *this;
	num_ = other.num_;
	return *this;
}

转换构造函数

1.转换构造函数是有单个参数的构造函数。带一个参数的构造函数可以分为普通构造函数(初始化)和转换构造函数(初始化、类型转化)
2.将其他类型转换为类类型
3.类的构造函数只有一个参数是非常危险的,因为编译器可以使用这种构造函数把参数的类型隐式转换为类类型。

#include <iostream>
#include "Test.h"
using namespace std;

int main()
{
	Test t(10);	//	调用带一个参数的构造函数,充当的是普通构造函数的功能。

	t = 20;	//	将20这个整数赋值给t对象。
			//	1.这时将会调用转换构造函数将20这个整数转换为类类型(生成一个临时对象)
			//	2.将临时对象赋值给t(调用=运算符)
	t.Display();

	return 0;
}

在这里插入图片描述

赋值与初始化区别

1.在初始化语句中的等号不是运算符。编译器对这种表示方法有特殊的解释。
2.赋值
3.Test& Test::operator=(const Test& other);
#include <iostream>
#include "Test.h"
using namespace std;

int main()
{
	Test t(10);	//	调用带一个参数的构造函数,充当的是普通构造函数的功能。

	Test t1 = 20;	//	等价Test t(20);

	return 0;
}

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include "Test.h"
using namespace std;

int main()
{
	Test t(10);	//	调用带一个参数的构造函数,充当的是普通构造函数的功能。

	Test t1 = 20;	//	等价Test t(20);这里的=不是运算符,表示初始化。

	t = 30;	//	赋值操作

	Test t2;
	t = t2;	// 赋值操作 t.operator=(t2);

	return 0;
}

在这里插入图片描述

explicit

1.只提供给类的构造函数使用的关键字
2.编译器不会把声明为explicit的构造函数用于隐式转换,它只能在程序代码中显示创建对象。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
编译不会通过。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值