【发布时间】:2018-03-09 07:28:11
【问题描述】:
我已经查看了其他几个问题,但我的案例似乎比我经历过的案例要简单得多,所以我会问我的案例。
学习.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");
}
上面的代码本身并没有输出任何错误。
但是,在将 Learn(0) 替换为 Learn(x) 后,我确实遇到了一些错误。它们是:
- 错误 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。我知道这只是练习,我对此很陌生,但实际上,我有点困惑为什么这不起作用。
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
您尝试在 .cpp 中指定 x(在 Learn ctor 中)的默认值。您应该在标题中定义它。
-
@ZeroUltimax 关于默认参数是正确的,但编译器抱怨的真正原因是它认为您正在尝试定义一个名为
Learn的函数。您不能像您尝试的那样调用构造函数。您需要使用Learn some_name(x);。 -
[OT]:
Learn::Learn(int x=0)在您的 cpp 中没有用,因为默认值仅在该 cpp 文件中可用。删除它,或将其放在您的标题中。
标签: c++ constructor compiler-errors most-vexing-parse