【发布时间】:2015-12-13 00:26:00
【问题描述】:
我有一个Rectangle 类,其中包含double 和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;
}
我不明白为什么调用operator double(),而不是operator std::string()。
据我所知,据C++ wikibook,
operator double 用于将Rectangle 对象转换为double。
那么这里发生了什么?是否与将int 传递给构造函数的事实有关?如果有,为什么?
【问题讨论】:
-
将矩形转换为双精度是什么意思。
-
我猜是 (double)r 之类的
-
@AlexGoft 不,另一个 Alex 的意思是“这意味着什么逻辑上?”。从表面上看,这个操作似乎毫无意义。
-
我怀疑他的意思是指区域,因为没有其他理由在示例中包含
getArea()函数。
标签: c++ operator-overloading implicit-conversion