对构造函数的困惑 - 预计会有';'

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文件中时,错误就消失了。你知道是什么原因造成的吗?

  1. 在标题
  2. 中不要使用using namespace
  3. 您将input作为宏常量并且类名相同。恐怕这就是你问题的根源。
  4. 优先使用构造函数初始化列表input(int sent) : s(sent) {}

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

更改宏名或类名