gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:49:07 27 4
gpt4 key购买 nike

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

学习.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/46454134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com