C++ visualc&x2B+;:没有默认构造函数

C++ visualc&x2B+;:没有默认构造函数,c++,constructor,compiler-errors,most-vexing-parse,C++,Constructor,Compiler Errors,Most Vexing Parse,我看了几个其他的问题,但我的问题似乎比我所经历的要简单得多,所以我会问我的问题 学习h: #ifndef LEARN_H #define LEARN_H class Learn { public: Learn(int x); ~Learn(); private: const int favourite; }; #endif Learn.cpp: #include "Learn.h" #include <iostream> using namespace

我看了几个其他的问题,但我的问题似乎比我所经历的要简单得多,所以我会问我的问题

学习h:

#ifndef LEARN_H
#define LEARN_H

class Learn
{
public:
    Learn(int x);
    ~Learn();

private:
    const int favourite;
};

#endif
Learn.cpp:

#include "Learn.h"
#include <iostream>
using namespace std;

Learn::Learn(int x=0): favourite(x)
{
    cout << "Constructor" << endl;
}

Learn::~Learn()
{
    cout << "Destructor" << endl;
}
#包括“Learn.h”
#包括
使用名称空间std;
学习::学习(intx=0):最喜欢的(x)
{
cout解析问题:

Learn(x);
被解析为

Learn x;
你应该使用

Learn{x};
建立您的临时或

Learn some_name{x};
//or
Learn some_name(x);

如果你想要一个实际对象。

好的,我找出了我所遇到的问题。我没有意识到调用是作为对象分配的一部分。C++中的符号似乎有点不同。 因此,显然应将

Learn(x)
替换为
Learn obj(x)


这种表示法与其他编程语言稍有不同,在其他编程语言中,您通常可以编写
className(inputs)variableName

我有类似的代码,但出现了不同的错误,因为我是在终端中使用Linux进行编译的。我的错误是:

error: conflicting declaration 'myObject str' 
error: 'str' has a previous declaration as 'const string  str'
当我尝试
myObject(str);

当然
Learn{x};
(在我的例子中是
myObject{str};
)将成功编译,但它会创建一个临时对象,然后在同一行中销毁它

这不是我想要做的。因此,另一种解决方案是创建一个新对象,如:

Learn var\u name=new Learn(x);


这样,您就可以引用它以备将来使用。

您试图指定默认值x(在学习工具中)在.cpp中,您应该改为在标题中定义它。@ZeroUltimax关于默认参数是正确的,但编译器抱怨的真正原因是它认为您试图定义一个名为
Learn
的函数。您不能像试图调用构造函数那样调用构造函数。您需要使用
了解一些名称(x);
[OT]:
Learn::Learn(int x=0)
在您的cpp中是无用的,因为默认值仅在该cpp文件中可用。请将其删除,或将其放在您的头中。最好给它一个名称:
Learn tmp{x};
@RustyX:这不再是临时的,而且打印的
“析构函数”暂停后会发生。可能使用额外的范围<代码> {学习tMP{x};} /Cuth>如果您想绝对命名它。@ JAROD42什么是临时的?对不起,有点新到C++。
error: conflicting declaration 'myObject str' 
error: 'str' has a previous declaration as 'const string  str'