对构造函数的困惑 - 预计会有';'
Confusion about constructors - expected a ';'
本文关键字:构造函数 更新时间:2023-10-16
不是把我的类放在与我的主函数相同的文件中,我试图使用#include。但是,当我这样做时,构造函数会出现错误。这是我的input.cpp文件:
#ifndef input
#define input
using namespace std;
#include <string>
#include <iostream>
class input
{
public:
input(int sent)
{
s = sent;
}
void read();
void store(string s);
private:
int s;
};
#endif
这是我的主要功能:
#include <iostream>
#include <string>
using namespace std;
#include "input.cpp"
int main()
{
cout<<"Hello, please enter your input"<<endl;
string sent;
getline(cin, sent);
cout<<sent;
input1 *newinput = new input1("hello");
system("pause");
return 0;
}
得到的错误是
构造函数体中的"intelliSense expected a '; "
。但是,当我将该类直接复制/粘贴到main.cpp文件中时,错误就消失了。你知道是什么原因造成的吗?
- 在标题 中不要使用
- 您将
input
作为宏常量并且类名相同。恐怕这就是你问题的根源。 - 优先使用构造函数初始化列表
input(int sent) : s(sent) {}
using namespace
UPDT
您可能需要构造函数能够接受字符串作为参数input(const std::string& str1) : str(str1) {}
,其中str
是处理字符串数据的类成员。
您将构造函数定义为具有一个int类型的形参
input(int sent)
{
s = sent;
}
,但试着调用它作为参数传递字符串字面值
input *newinput = new input("hello");
类型为const char[6]
的字符串字面值不能隐式转换为int类型,并且该类没有其他接受字符数组作为参数的构造函数。
EDIT:
您更改了原始帖子几次,所以现在不清楚是否在语句
input1
input1 *newinput = new input1("hello");
是打字错误,或者是其他类型。
还有一个与类名同名的宏定义
#ifndef input
#define input
更改宏名或类名
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为