C++ 函数定义和变量声明不匹配?
C++ function definition and variable declaration mismatch?
考虑这个非常简单的代码:
#include <memory>
class Foo
{
public:
Foo() {};
};
class Bar
{
public:
Bar( const std::shared_ptr<Foo>& foo ) {}
};
int main()
{
Foo* foo = new Foo;
Bar bar( std::shared_ptr<Foo>( foo ) );
return 0;
}
为什么 Visual Studio 报告
warning C4930: 'Bar bar(std::shared_ptr<Foo>)': prototyped function not called (was a variable definition intended?)
并且没有创建 bar
对象...这行 Bar bar( std::shared_ptr<Foo>( foo ) );
如何被解释为函数定义?
我检查了 Do the parentheses after the type name make a difference with new? and also C++: warning: C4930: prototyped function not called (was a variable definition intended?),但我觉得我的问题在这里有所不同,因为我没有使用语法 Foo()
也没有使用 Bar()
.
编辑:注意编译成功:
Foo* foo = new Foo;
std::shared_ptr<Foo> fooPtr( foo );
Bar bar( fooPtr );
这个问题是关于 C++'s most vexing parse 的。声明:
Bar bar( std::shared_ptr<Foo>( foo ) );
声明一个名为 bar
的函数 returns Bar
并接受一个名为 foo
类型为 std::shared_ptr<Foo>
的参数。
最里面的括号没有作用。就好像你会写以下内容:
Bar bar( std::shared_ptr<Foo> foo);
假设使用 C++11(因为您已经在使用 std::shared_ptr
),您可以使用 大括号语法 而不是 圆括号 :
Bar bar(std::shared_ptr<Foo>{foo});
这实际上会构造一个 Bar
类型的对象 bar
,因为上面的语句由于括号的原因不能被解释为声明。
考虑这个非常简单的代码:
#include <memory>
class Foo
{
public:
Foo() {};
};
class Bar
{
public:
Bar( const std::shared_ptr<Foo>& foo ) {}
};
int main()
{
Foo* foo = new Foo;
Bar bar( std::shared_ptr<Foo>( foo ) );
return 0;
}
为什么 Visual Studio 报告
warning C4930: 'Bar bar(std::shared_ptr<Foo>)': prototyped function not called (was a variable definition intended?)
并且没有创建 bar
对象...这行 Bar bar( std::shared_ptr<Foo>( foo ) );
如何被解释为函数定义?
我检查了 Do the parentheses after the type name make a difference with new? and also C++: warning: C4930: prototyped function not called (was a variable definition intended?),但我觉得我的问题在这里有所不同,因为我没有使用语法 Foo()
也没有使用 Bar()
.
编辑:注意编译成功:
Foo* foo = new Foo;
std::shared_ptr<Foo> fooPtr( foo );
Bar bar( fooPtr );
这个问题是关于 C++'s most vexing parse 的。声明:
Bar bar( std::shared_ptr<Foo>( foo ) );
声明一个名为 bar
的函数 returns Bar
并接受一个名为 foo
类型为 std::shared_ptr<Foo>
的参数。
最里面的括号没有作用。就好像你会写以下内容:
Bar bar( std::shared_ptr<Foo> foo);
假设使用 C++11(因为您已经在使用 std::shared_ptr
),您可以使用 大括号语法 而不是 圆括号 :
Bar bar(std::shared_ptr<Foo>{foo});
这实际上会构造一个 Bar
类型的对象 bar
,因为上面的语句由于括号的原因不能被解释为声明。