今天一个奇怪的 C++ 编译器行为让我感到惊讶。
class Foo {
friend ostream& operator << (ostream& os, const Foo& rhs)
{
return os << sizeof(rhs) << endl;
}
};
struct Bar { };
int main()
{
Foo f(Bar());
cout << f;
return 0;
}
显然,上面的代码编译得很好,即使没有
Foo(const Bar&);
c'tor 定义。使用 -Wall 编译表明编译器解释了表达式
Foo f(Bar());
作为函数的原型(prototype)
Foo f(Bar (*)())
而不是用于创建 Foo 类型对象的表达式。
这里真正的陷阱(规则)是什么??
最佳答案
Foo f(Bar());
这里编译器假设是一个函数调用,作为 C++“最令人烦恼的解析”的结果。
你所能做的就是在你的对象周围再放一个括号。
Foo f((Bar()));
如果您查看 C++11 文档,则有更多方法可以避免这种行为。
关于C++ 对象创建或函数原型(prototype)声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26927486/