#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
{}
// magnitude : usual function style
double mag()
{
return getMag();
}
// magnitude : conversion operator
operator int ()
{
return getMag();
}
private:
// class helper to get magnitude
double getMag()
{
return sqrt(real * real + imag * imag);
}
};
int main()
{
// a Complex object
Complex com(3.0, 4.0);
// print magnitude
cout << com.mag() << endl;
// same can be done like this
cout << com << endl;
}
我不明白编译器是如何解析为 cout << com << endl;
调用转换运算符的.
我也可以在同一个类中有多个转换运算符。在这种情况下将如何解决?
最佳答案
您已将转换运算符声明为 int
.由于此运算符不是显式的,因此编译器在寻找 ostream::operator<<
的最佳重载时会考虑它.请记住,C++ 编译器始终会尝试自动转换类型以找到匹配的调用,包括转换构造函数、转换运算符和隐式类型转换。
如果您不想要这种行为,那么从 C++11 开始,您可以将运算符标记为 explicit
:
explicit operator int() {
return getMag();
}
关于您问题的第二部分,如果有多个转换同样好,则会调用编译错误。如果你添加了,比方说,operator double
, 那么因为存在 ostream::operator(double)
, 调用将是模棱两可的,你需要投 com
到您想要的类型。
关于c++ - 使用转换运算符 cout 一个类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38225208/