参考下面程序的结果:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// 默认构造函数
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 比较两个复数的方法
bool operator == (Complex rhs) {
return (real == rhs.real && imag == rhs.imag) ? true : false;
}
};
int main() {
// 复数的对象
Complex com1(3.0, 0.0);
if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return 0;
}
运行结果:
Same
前面已经提到过,C++中,如果一个构造函数可以只需要传入一个参数来调用,则这个构造函数可以变成转换构造函数。
我们可以避免这种隐式的转换,因为它可能导致未知的行为。我们可以在构造函数中使用explicit关键字。
这样的话,下面的程序会编译失败。
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// 默认构造函数
explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 比较两个复数的成员函数
bool operator== (Complex rhs) {
return (real == rhs.real && imag == rhs.imag) ? true : false;
}
};
int main() {
// 定义一个复数对象
Complex com1(3.0, 0.0);
if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return 0;
}
编译失败,输出下面提示信息。
gcc4.8.5 + CentOS7.2输出:
error: no match for 'operator==' (operand types are 'Complex' and 'double')
visual studio 2015:
error C2679: 二进制“==”: 没有找到接受“double”类型的右操作数的运算符(或没有可接受的转换)
我们仍然可以使用强制转换将double值转换为复数对象,但是至少这需要显式地去进行转换。
例如,下面代码可以正常运行:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
bool operator== (Complex rhs) {
return (real == rhs.real && imag == rhs.imag) ? true : false;
}
};
int main() {
Complex com1(3.0, 0.0);
if (com1 == (Complex)3.0) //这里需要显式地进行转换
cout << "Same";
else
cout << "Not Same";
return 0;
}
运行结果:
Same