c++ - 视觉 C++ : No default constructor

标签 c++ constructor compiler-errors most-vexing-parse

我已经看过其他几个问题来问这个问题,但我的案例似乎比我经历过的案例简单得多,所以我会问我的案例。

学习.h:

#ifndef LEARN_H
#define LEARN_H

class Learn
{
public:
    Learn(int x);
    ~Learn();

private:
    const int favourite;
};

#endif

学习.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:Learn 类不存在默认构造函数
  • Error C2371 : 'x' : 重新定义;不同的基本类型
  • Error C2512 : 'Learn': 没有合适的默认构造函数可用

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

如有任何帮助,我们将不胜感激。

最佳答案

解析问题:

Learn(x);

被解析为

Learn x;

你应该使用

Learn{x};

建立你的临时或

Learn some_name{x};
//or
Learn some_name(x);

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

关于c++ - 视觉 C++ : No default constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742833/

相关文章:

c++ - 为什么windows让你在整个屏幕上画画?

objective-c - Objective-C 的新手。收到 "may not respond to ' 新警告。 “导致段错误的构造函数

java - 将图像拖放到Jpanel中并将其放入应用程序目录中

ios - 无法构建调试方案 - Apple Mach-O 链接器错误。链接器命令失败,退出代码为 1

c# - 为什么在此 C# 表达式中不使用括号时 && 运算符会中断?

c++ - g++ 优化 -O3 导致奇怪的堆栈转储错误?

c++ - 为什么我的程序在运行后输出一个 % 符号?

使用 operator new : What are the methods of detecting and processing allocation errors? 的 C++ 内存分配

具有默认参数的 C++ 基类构造函数

c++ - C++错误:没有匹配的构造函数用于初始化