操作符double()的使用不明确
Unclear use of operator double()
我有一个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
,这样就可以选择。
string重载没有被选中,也没有被认为是不义的,因为string的operator <<
是成员函数,不包含在cout
的成员重载和非成员重载集合中。如果我们注释掉operator double
,我们可以看到我们得到一个编译器错误。
如果我们想要调用operator string
,那么我们需要显式地将r
强制转换为字符串。<<kbd>生活例子/kbd>
由于您没有为Rectangle
提供operator<<
重载,编译器会考虑其他重载,这些重载的实参可以转换为形参类型。
如果任何重载都是模板,则在重载解析之前对它们进行模板实参替换。编译器尝试从提供给函数的实参类型中推断出模板形参。
没有考虑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);
模板实参替换不考虑用户定义的转换,因此编译器不能从Rectangle
类型推导出CharT
、Traits
或Allocator
类型,因此该重载不参与重载解析。(回想一下,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);
与其他基本类型的重载相比,双重载没有什么特别之处。在这种情况下,它是唯一可用的原语重载。对于int、char等类型,编译器的行为是一样的。
注意,如果有多个基本类型重载,编译器会抛出
error: ambiguous overload for 'operator<<' ...
- Visual C++(VS2017)中用户定义的转换不明确
- 重载类方法的不明确调用
- 为函数定义符号不明确的指针参数
- 父类的私有函数会导致对具有相同名称和相似参数的子类中的公共函数的不明确调用
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- C++ 编译器错误:P1LinkedList.cpp:145:错误:重载的"to_string(int&)"调用不明确
- 对重载函数find_first_not_of的不明确调用
- 不明确的成员模板查找
- gcc出现不明确的模板实例化错误
- 调用'Node'构造函数是不明确的
- 如何解决不明确的运算符过载问题?
- 使用 nullptr 调用重载方法是不明确的
- "fpclassify":对重载函数的不明确调用
- 对"列表"的引用不明确,包括头文件
- 删除全局隐式函数 - 避免使用不明确的运算符
- 当接收到不明确的规范时,表示图的邻接列表的数据结构
- 错误:重载的"abs(double)"调用不明确
- 重载的函数调用double不明确
- 操作符double()的使用不明确
- 重载的'qHash(const double&)'的调用是不明确的