C++运算符重载(5) 重载== explicit避免隐式转换

有的时候程序中存在隐藏式转换

 

#include<iostream>
using namespace std;

class myComplex {
private:
	int real;   //复数的实部
	int image;  //复数的虚部
public:
	myComplex(int real = 0, int image = 0) {
		this->real = real;
		this->image = image;
	}
	friend bool operator == (const myComplex &obj1, const myComplex &obj2);
};

bool operator == (const myComplex &obj1, const myComplex &obj2) {
	if (obj1.real == obj2.real && obj1.image == obj2.image)
		return true;
	return false;
}

int main() {

	myComplex TestA(3,0);
	myComplex TestB(10,0);

	if (TestA == 3) {
		cout << "SAME" << endl;
	}
	else {
		cout << "NOT SAME" << endl;
	}

	system("PAUSE");
	return 0;


我们通过重载操作符 == 来判断两个自定义的类:复数是否相等

 

 

myComplex(int real = 0, int image = 0)

在构造函数中,我们给形参定义了默认值 所以在生成对象时 如果不指定形参 便会使用默认值

 

C++中,如果构造函数可以只传入一个参数来调用,则会发生隐式转换

 

if (TestA == 3)

在上面行代码中 将3传入重载操作符函数 构造函数便会构造一个3,0的myComplex对象, 这便发生了隐式转换(将int型转为myComplex型)

 

我们可以通过使用explicit来避免隐式转换

 

explicit myComplex(int real = 0, int image = 0) {
		this->real = real;
		this->image = image;
	}


这时必须指明类型

 

 

	myComplex TestA(3,0);
	myComplex TestB(10,0);

	if (TestA == (myComplex)3) {    //必须指明类型
		cout << "SAME" << endl;
	}
	else {
		cout << "NOT SAME" << endl;
	}

 

例子补充:

class mystring {
public:
	explicit mystring(const char* s = nullptr) {
		cout << "mystring(const char* s = nullptr)" << endl;
	}
};

这时候就无法进行隐式转换了

	mystring s("china");   //显示转化,这是被允许的
	mystring s2 = "china";   //这是一个隐式转化,从const char* 到mystring,通过
	                         //explicit关键字可以进行禁止

 

 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值