Mad*_*iac 2 c++ constructor compiler-errors most-vexing-parse
我已经看了几个问这个问题的其他问题,但我的情况似乎比我经历过的情况简单得多,所以我会问这个问题.
Learn.h:
#ifndef LEARN_H
#define LEARN_H
class Learn
{
public:
Learn(int x);
~Learn();
private:
const int favourite;
};
#endif
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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");
}
Run Code Online (Sandbox Code Playgroud)
上面的代码本身不会输出任何错误.
不过,我后,我得到更换一对夫妇的错误Learn(0)有Learn(x).他们是:
no default constructor exists for class Learn'x' : redefinition; different basic types'Learn' : no appropriate default constructor available有什么理由吗?我真的想在其中输入整数变量x而不是0.我知道这只是练习而且我是新手,但实际上,我有点困惑为什么这不起作用.
任何帮助将不胜感激,谢谢.
解析问题:
Learn(x);
Run Code Online (Sandbox Code Playgroud)
被解析为
Learn x;
Run Code Online (Sandbox Code Playgroud)
你应该用
Learn{x};
Run Code Online (Sandbox Code Playgroud)
建立你的临时或
Learn some_name{x};
//or
Learn some_name(x);
Run Code Online (Sandbox Code Playgroud)
如果你想要一个实际的对象.