c++ - 使用转换运算符 cout 一个类对象

标签 c++

#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/

相关文章:

c++ - 如何判断c++ vector中的值类型(int或double)?

c++ - 指向函数和派生类的指针

c++ - thread_local 变量初始化

c++ - std::map: find(key)->second 比 [] 运算符快吗?

c++ - 在静态函数c++中获取类的类型

c++ - 广义霍夫变换和 OpenCv

c++ - 虚函数和泛型编程

c++ - QT Creator 不允许我保存任何东西

c++ - 什么是冒名顶替者设计模式?

c++ - 是否可以在 C++ 中序列化和反序列化一个类?