gpt4 book ai didi

c++ - 运算符 double() 的使用不清楚

转载 作者:IT老高 更新时间:2023-10-28 22:37:26 25 4
gpt4 key购买 nike

我有一个 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 <<因为字符串是成员函数,不包含在 member overload 中和 non member overload一组cout .如果我们注释掉 operator double我们可以看到we get a compiler error .

如果我们想要 operator string调用然后我们需要显式转换 r成一个字符串。 Live Example

关于c++ - 运算符 double() 的使用不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32608226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com