Visual C++: No default constructor(Visual C++:没有默认构造函数)
问题描述
我已经看过其他几个问这个问题的问题,但我的案例似乎比我经历过的要简单得多,所以我会问我的案例.
I've looked at a couple other questions asking this, but mine seems to be a lot simpler of a case then the ones I've been through, so I'll ask my case for this.
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;
}
源.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");
}
上面的代码本身并没有输出任何错误.
The above code in itself does not output any error.
但是,在将 Learn(0) 替换为 Learn(x) 后,我确实遇到了一些错误.它们是:
However, I do get a couple errors after I replace Learn(0) with Learn(x). They are:
- 错误 E0291:
不存在类 Learn 的默认构造函数 - 错误 C2371:
'x' : 重新定义;不同的基本类型 - 错误 C2512:
'Learn' : 没有合适的默认构造函数可用
有什么原因吗?我真的想在其中实际输入整数变量 x 而不是 0.我知道这只是练习,我是新手,但实际上,我对为什么这不起作用感到有些困惑.
Any reason for this? I really want to actually input the integer variable x inside it rather than the 0. I know this is only practice and I'm new to this, but really, I'm a little confused as to why this doesn't work.
任何帮助将不胜感激,谢谢.
Any help would be appreciated, thanks.
推荐答案
解析问题:
Learn(x);
被解析为
Learn x;
你应该使用
Learn{x};
建立你的临时或
Learn some_name{x};
//or
Learn some_name(x);
如果你想要一个实际的对象.
if you want an actual object.
这篇关于Visual C++:没有默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Visual C++:没有默认构造函数
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
