C ++函数定义和变量声明不匹配?

编程入门 行业动态 更新时间:2024-10-12 10:24:07
本文介绍了C ++函数定义和变量声明不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下非常简单的代码:

Consider this very simple code:

#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报告

Why does Visual Studio reports

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)); 怎么解释为函数定义?

and there is no bar object created...how can this line Bar bar( std::shared_ptr<Foo>( foo ) ); be interpreted as a function definition?

我检查了做括号类型名称之后是否与new有所不同?以及 C ++:警告:C4930:未调用原型函数(是否打算使用变量定义?),但是我觉得这里的问题有所不同,因为我没有使用语法 Foo()或 Bar().

I checked 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?), but I feel my problem is different here as I did not use the syntax Foo() nor Bar().

请注意,它可以成功编译:

Note that it successfully compiles:

Foo* foo = new Foo; std::shared_ptr<Foo> fooPtr( foo ); Bar bar( fooPtr );

推荐答案

此问题与 C ++最令人讨厌的解析有关.声明:

Bar bar( std::shared_ptr<Foo>( foo ) );

声明一个名为 bar 的函数,该函数返回 Bar 并接受名为 std :: shared_ptr< Foo>类型的名为 foo 的参数..

declares a function called bar that returns Bar and takes an argument called foo of type std::shared_ptr<Foo>.

最里面的括号无效.就像您将编写以下内容一样:

The innermost parenthesis have no effect. It is as if you would have written the following:

Bar bar( std::shared_ptr<Foo> foo);

假设使用C ++ 11(因为您已经在使用 std :: shared_ptr ),则可以使用括号语法代替括号:

Bar bar(std::shared_ptr<Foo>{foo});

这实际上将构造一个类型为 Bar 的对象 bar ,因为上面的语句由于括号不能被解释为声明.

This would actually construct an object bar of type Bar, since the statement above can't be interpreted as a declaration because of the braces.

更多推荐

C ++函数定义和变量声明不匹配?

本文发布于:2023-11-15 14:19:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   函数   不匹配   定义   声明

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!