不清楚使用运算符double() [英] Unclear use of operator double()

查看:100
本文介绍了不清楚使用运算符double()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rectangle类,同时具有对doublestd::string的转换运算符:

class Rectangle
{
public:
    Rectangle(double x, double y) : _x(x), _y(y) {}
    operator std::string ();
    operator double ();
private:
    double _x, _y;
    double getArea() {return _x * _y;}
};

int main()
{
    Rectangle r(3, 2.5);
    cout << r << endl;
    return 0;
}

我不明白为什么调用operator double()而不是operator std::string(). 据我所知,根据 C ++ Wikibook operator double用于将Rectangle对象转换为double.

那么这是怎么回事?它与int传递给构造函数有关吗?如果是这样,为什么?

解决方案

您没有将矩形输出到流的运算符. cout确实有一个需要double的重载,并且您的类可以隐式转换为double以便选择.

之所以未选择字符串重载并且不将其视为歧义,是因为字符串的operator <<是成员函数,并且不包含在非成员超载一组cout.如果我们注释掉operator double,我们会看到我们会收到编译器错误.

如果要调用operator string,则需要将r显式转换为字符串. 在线示例

I have a Rectangle class with conversion operators to both double and std::string:

class Rectangle
{
public:
    Rectangle(double x, double y) : _x(x), _y(y) {}
    operator std::string ();
    operator double ();
private:
    double _x, _y;
    double getArea() {return _x * _y;}
};

int main()
{
    Rectangle r(3, 2.5);
    cout << r << endl;
    return 0;
}

I don’t understand why operator double() is invoked, rather than operator std::string(). As far as I know, according to C++ wikibook, operator double is used to convert Rectangle objects to double.

So what's going on here? Is it related to the fact that an int is passed to the constructor? If so, why?

解决方案

You do not have an operator to output the rectangle to the stream. cout does have an overload that takes a double and your class can be implicitly converted to a double so that is chosen.

The reason the string overload is not selected and is not considered as an ambiguity is because operator << for a string is a member function and is not included in the member overload and non member overload set of cout. If we comment out the operator double we can see we get a compiler error.

If we want to have the operator string called then we would need to explicitly cast r into a string. Live Example

这篇关于不清楚使用运算符double()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆