Visual C ++:没有默认构造函数 [英] Visual C++: No default constructor
问题描述
我已经问了几个其他问题,但是我的情况似乎比我经历过的要简单得多,所以我将为此问题询问我的情况。
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:
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;
}
Source.cpp:
Source.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)
替换为后,我确实遇到了一些错误学习(x)
。它们是:
However, I do get a couple errors after I replace Learn(0)
with Learn(x)
. They are:
- Error E0291:
no default constructor exists for class Learn
- Error C2371:
'x' : redefinition; different basic types
- Error C2512:
'Learn' : no appropriate default constructor available
任何原因吗?我真的很想在其中输入整数变量 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.
这篇关于Visual C ++:没有默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!