Visual C++:没有默认构造函数

我已经看过其他几个问这个问题的问题,但我的案例似乎比我经历过的要简单得多,所以我会问我的案例.

I've looked at a couple other questions asking this, but mine seems to be a lot simpler of a case then the ones I've been through, so I'll ask my case for this.

Learn.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;
}

源.cpp:

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

int main() {
    cout << "What's your favourite integer? "; 
    int x; cin >> x;
    Learn(0);

    system("PAUSE");
}

上面的代码本身并没有输出任何错误.

The above code in itself does not output any error.

但是,在将 Learn(0) 替换为 Learn(x) 后,我确实遇到了一些错误.它们是:

However, I do get a couple errors after I replace Learn(0) with Learn(x). They are:

  • 错误 E0291:不存在类 Learn 的默认构造函数
  • 错误 C2371:'x' : 重新定义;不同的基本类型
  • 错误 C2512:'Learn' : 没有合适的默认构造函数可用

有什么原因吗?我真的想在其中实际输入整数变量 x 而不是 0.我知道这只是练习,我是新手,但实际上,我对为什么这不起作用感到有些困惑.

Any reason for this? I really want to actually input the integer variable x inside it rather than the 0. I know this is only practice and I'm new to this, but really, I'm a little confused as to why this doesn't work.

任何帮助将不胜感激,谢谢.

Any help would be appreciated, thanks.

推荐答案

解析问题:

Learn(x);

被解析为

Learn x;

你应该使用

Learn{x};

建立你的临时或

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

如果你想要一个实际的对象.

if you want an actual object.

相关文章