【发布时间】:2020-02-19 16:36:01
【问题描述】:
class B{
float floatVar;
public:
B(float a):floatVar(0.0){
floatVar = a;
}
operator int(){ // Consider this as line A
return floatVar;
}
};
int main()
{
B floatObj(5.5);
cout << floatObj; // Consider this as line B
return 0;
}
当我重载 int() 时 cout 显示 5,当我在 A 行中将 int() 替换为 float() 时,程序显示 5.5。 我想知道它是如何自动调用 cout 中的 int() typecaster 或 float() 的?
【问题讨论】:
-
在重载解析中找到
std::ostream::operator<<,并且它具有采用float、int等的重载,因此尝试从floatObj到每个重载的隐式转换。 en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt -
@M.M 我又添加了一个数据成员,但现在它不起作用?发生了什么事?
-
等一下,让我找到我的水晶球
标签: c++