- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一个 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
传递给构造函数的事实有关?如果有,为什么?
最佳答案
您没有将矩形输出到流的运算符。 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/
MVC3 中的助手是否在 Controller 和 View 中使用? 助手是放置常用 Controller 方法的正确位置吗? 我想创建一个通用方法来获取数据库中的所有子子 ID,并确保它位于正确的
有人可以阐明这两者之间的区别吗,因为它们存在于执行上下文中?我很难阅读 ECMA 262 v 5规范并清楚地看到差异。 谢谢你, 最佳答案 两者都是执行上下文的组件(相同类型),但它们有不同的用途(f
我是一名优秀的程序员,十分优秀!