C++ 为什么拆分为两行时不起作用?

C++ 为什么拆分为两行时不起作用?,c++,C++,这一行: std::auto_ptr<Ogre::Root> lRoot (new Ogre::Root(lConfigFileName, lPluginsFileName, lLogFileName)); std::auto_ptr lRoot(新的Ogre::Root(lConfigFileName、lpluginfilename、lLogFileName)); 很好。 但是,当我这样做时,它不会: std::auto_ptr<Ogre::Root> lRoot;

这一行:

std::auto_ptr<Ogre::Root> lRoot (new Ogre::Root(lConfigFileName, lPluginsFileName, lLogFileName));
std::auto_ptr lRoot(新的Ogre::Root(lConfigFileName、lpluginfilename、lLogFileName));
很好。 但是,当我这样做时,它不会:

std::auto_ptr<Ogre::Root> lRoot;
lRoot (new Ogre::Root(lConfigFileName, lPluginsFileName, lLogFileName));
std::auto_ptr lRoot;
lRoot(新的Ogre::Root(lConfigFileName,lpluginfilename,lLogFileName));
它报告:
错误:调用“(std::auto_ptr)(Ogre::Root*)”时没有匹配项。

就我有限的理解而言,这些不应该做同样的事情吗?还是我错过了一些重要的东西?

它们不是一回事

您不仅仅是将语句拆分为两行。这是两种不同的说法

可以将第一条语句拆分为两行,如下所示:

std::auto_ptr<Ogre::Root> lRoot
    (new Ogre::Root(lConfigFileName, lPluginsFileName, lLogFileName));
std::auto_ptr lRoot
(新的Ogre::Root(lConfigFileName、lpluginfilename、lLogFileName));

由于忽略了多个空格,因此它可以正常编译。

这两个代码段之间几乎没有关系

第一个声明并初始化变量
lRoot
,在那里看不到任何内容


第二个代码段在第一行声明并默认初始化
lRoot
,但随后它继续调用
lRoot
,使用类型为
Ogre::root*
的参数。由于
std::auto_ptr
是一个
操作符()
,编译器会产生给定的错误。

第一条语句是带有初始化的变量
lRoot
的声明(使用括号中初始化器的语法)

第二个是默认初始化变量
lRoot
的声明,然后调用变量上的
operator()
。(请注意,它没有定义这样的运算符)

要将其拆分为两行(仍然作为一条语句),只需在允许空白的任何位置插入换行符即可:

std::auto_ptr<Ogre::Root> lRoot(
  new Ogre::Root(lConfigFileName, lPluginsFileName, lLogFileName));
std::auto_ptr lRoot(
新Ogre::Root(lConfigFileName,lpluginfilename,lLogFileName));
要将其实际拆分为声明和赋值(请注意,拆分时不能是初始化),可以执行以下操作:

std::auto_ptr<Ogre::Root> lRoot;
lRoot.reset(new Ogre::Root(lConfigFileName, lPluginsFileName, lLogFileName));
std::auto_ptr lRoot;
reset(新的Ogre::Root(lConfigFileName,lpluginfilename,lLogFileName));

如何将其拆分为两行。(或者在a.h中声明,在.cpp中初始化构造函数)上次我检查时,Ogre有自己的智能指针类。你为什么不用呢?无论如何,
auto_ptr
已被弃用。算了吧。这就是食人魔教程告诉我要做的事xD,我只是重新构造了一点代码。很好,它不仅回答了问题,而且给出了一个修复,会尽快接受。@handuel:将来,如果你想要修复,最好还是问一下。有很多问题,海报不想修复某些东西(例如,有一个明显的解决方法),而是想理解它。@MooingDuck:Angew在他的回答中已经提到了
.reset
,因此基本上是可以理解的。我没有,因为问题只问“为什么?”。没错,他只问为什么,但OP显然不知道他在做什么,需要朝着正确的方向推动。