我有一个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++上网本,operator double用于将Rectangle对象转换为double。
这是怎么回事?这与int被传递给构造函数的事实有关吗?如果是,为什么?
发布于 2015-09-16 13:54:15
由于您没有为operator<<提供Rectangle重载,所以编译器考虑可以将参数转换为参数类型的其他重载。
如果任何重载都是模板,那么在重载解析之前,模板参数替换将发生在它们身上。编译器试图从提供给函数的参数类型中推断模板参数。
不考虑string重载,因为模板参数替换失败
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);模板参数替换不考虑用户定义的转换,因此编译器无法从类型CharT、Traits或Allocator中推断出类型Rectangle,因此该重载不参与重载解析。(回想一下,std::string只是std::basic_string<char, std::char_traits<char>, std::allocator<char>>的一个类型。)
因此,有一个operator<<重载比任何其他重载都更匹配,那就是double重载。不是模板,而是类模板的成员函数。
basic_ostream<CharT, Traits>& basic_ostream<CharT, Traits>::operator<<(double);发布于 2019-01-16 10:57:42
与其他原始类型的重载相比,双重重载没有什么特别之处。在这种情况下,它是唯一可用的原始重载。编译器对于int、char等的行为也是一样的。
注意,如果我们有多个原语类型重载,编译器将抛出
error: ambiguous overload for 'operator<<' ...https://stackoverflow.com/questions/32608226
复制相似问题