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

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).他们是:

  • 错误E0291: no default constructor exists for class Learn
  • 错误C2371:'x' : redefinition; different basic types
  • 错误C2512:'Learn' : no appropriate default constructor available

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

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

Jar*_*d42 8

解析问题:

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)

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

  • @RustyX:这不再是一个临时的,"Destructor"的打印将在暂停后发生.可能使用额外范围`{Learn tmp {x};}`如果你想要完全命名它. (2认同)