Visual C++:没有默认的构造函数
问题描述:
我已经看过其他几个问题,但我的情况似乎比我经历过的情况简单很多,所以我会问我的情况。Visual C++:没有默认的构造函数
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;
}
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");
}
本身上面的代码不输出任何误差。
但是,在将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
。我知道这只是练习,我是新手,但真的,我有点困惑,为什么这不起作用。
任何帮助,将不胜感激,谢谢。
答
好的,我想出了我遇到的问题。我没有意识到这个调用是作为对象分配的一部分完成的。 C++中的符号似乎有点不同。
所以Learn(x)
显然应该用Learn obj(x)
代替。
这种表示方法与其他编程语言有所不同,您可以在其中编写className(inputs) variableName
。
您试图在.cpp中指定x的默认值(在Learn ctor中)。你应该在头文件中定义它。 – ZeroUltimax
@ZeroUltimax对于默认参数是正确的,但编译器抱怨的真正原因是它认为你正在试图定义一个名为'Learn'的函数。你不能像你想要的那样调用构造函数。你需要使用'Learn some_name(x);'。 – Jonesinator
[OT]:'Learn :: Learn(int x = 0)'在你的cpp中没用,因为默认值只在该cpp文件中可用。删除它,或将其放置在标题中。 – Jarod42