转换构造函数调用没有参数的函数

时间:2015-06-06 17:03:35

标签: 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 double ()
    {
        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;"调用funtion mag()。请帮忙。如果我将函数mag()更改为mag (int i),那么同样的输出。

3 个答案:

答案 0 :(得分:2)

永远不会调用

mag()。您的双转化运算符会调用getMag(),这就是调用mag()的原因。

当您致电cout << com << endl时,您的operator <<课程没有超载Complex。这会导致编译器查找operator <<支持的隐式转换。你的复杂类在这里重载了双转换运算符:

operator double ()
{
    return getMag();
}

正如您所看到的那样,双转换运算符会调用getMag()这就是为什么看起来正在调用mag()

答案 1 :(得分:1)

声明

cout<<com<<endl;

不会致电Complex::mag()。它正在调用转换运算符operator double();

答案 2 :(得分:0)

该类有转换运算符

operator double ()
{
    return getMag();
}

因此,如果您有一个名为Complex的{​​{1}}类型的对象,则在语句

com

将调用转换运算符,将对象std::cout << com << std::endl; 转换为double类型的对象。

如果您将使用说明符com

声明运算符
explicit

然后上面的陈述将无法编译。

相关问题