有的时候程序中存在隐藏式转换
#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关键字可以进行禁止