【发布时间】:2016-02-08 01:13:02
【问题描述】:
用 g++ 5.3.1 尝试 C++11 有一段时间了...
我以为我理解隐式转换运算符。一般来说,
如果我定义了Class3::operator Class2(),那么我可以将Class3 直接 传递给任何采用Class2 的函数。这似乎
99% 的时间都在工作……但我遇到了一个简单的例子
事实并非如此。
class Class1 {};
class Class2 {
public:
inline friend Class1 & operator<<(Class1 & a, Class2 const& c)
{return a;}
};
class Class3 {
public:
inline operator Class2() const {return Class2();}
};
void Foo(Class2 c) {}
int main()
{
Class1 c1;
Class3 c3;
// g++ does not like this:
// error: no match for 'operator<<' (operand types are 'Class1' and 'Class3')
// c1 << c3;
// g++ likes these just fine:
Foo(c3);
c1 << Class2(c3);
}
任何想法我做错了什么? 请帮忙!谢谢。
【问题讨论】:
-
您还没有为 Class3 定义
<<运算符重载,因此 g++ 不喜欢它。您将 Class3c3转换为 Class2,这是您实现的已定义转换运算符。 g++ 喜欢它,因为你定义了它。像 g++ 一样。 -
你得到什么错误信息?
-
@Poriferous 我看不出这有什么解释。
-
> 你得到什么错误信息
-
main.cpp: In function 'int main()': main.cpp:19:6: error: no match for 'operator
标签: c++ c++11 casting implicit-conversion