【发布时间】:2017-11-09 11:36:33
【问题描述】:
从the answer,我了解到std::string只是std::basic_string<char, std::char_traits<char>, std::allocator<char>>的typedef,模板参数替换不考虑用户定义的转换,所以编译器无法从类型中推断出CharT、Traits或Allocator类型矩形,所以这个重载不参与重载决议。
现在我用 std::basic_string, std::allocator> 代替 std::string:
class Rectangle
{
public:
Rectangle(double x, double y) : _x(x), _y(y) {}
operator std::basic_string<char, std::char_traits<char>, std::allocator<char>> () {
return std::basic_string<char, std::char_traits<char>, std::allocator<char>>(to_string(_x) + " " + to_string(_y));
}
//operator double() {
// return _x;
//}
private:
double _x, _y;
double getArea() { return _x * _y; }
};
int main()
{
Rectangle r(3, 2.5);
cout << r << endl;
return 0;
}
它仍然失败。为什么?
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);
【问题讨论】:
-
你可以定义
std::ostream& operator<< (std::ostream& stream, const Rectangle& rectangle)或者使用cout << (string)r
标签: c++