我是编程新手.在编译包含.h文件中的类定义的代码后,我不断收到错误消息



我试图调用自定义类的成员函数,但不断收到错误消息:

应在First_name之前使用主表达式Middle_name之前应为主表达式姓氏前应为主表达式

这是main cpp:的代码

#include <iostream >
#include <People.h>
auto NAME = P.Name_Input( std:string First_name, std::string Middle_name, std::string Surname) ;
std::cout<<NAME<<std::endl;

这是头文件:

class Person{
public:
std::string Name_Input(std::string First_name, std::string Middle_name, std::string Surname);
} ;

头文件编译得很好,并且已经链接到.cpp文件来定义方法,该部分也很好地工作。我的问题是main.cpp文件。

main.cppPeople.h都没有定义std::string,所以编译器不知道它是什么。

您需要将#include <string>添加到People.h:

#ifndef People_H
#define People_H
#include <string> // <-- add this
class Person{
public:
std::string Name_Input(std::string First_name, std::string Middle_name, std::string Surname);
};
#endif

一般经验法则是,任何需要使用另一个源文件中定义的类型的源文件都应该#include该另一个文件(除非使用前向声明就足够了,例如中断循环引用时(。请参阅依赖于以传递方式包含标头是一种好的做法吗?。这意味着main.cpp也应该有一个#include <string>语句,即使People.h(或main.cpp使用的任何其他标头(已经有了自己的#include <string>语句。

此外,您在main()中使用std::string也是错误的。将变量传递给函数或类方法时,不要包含类型名。仅在变量或函数参数的声明中使用类型名称。

试试这个:

#include <iostream>
#include <string> // <-- add this
#include "People.h"
int main()
{
Person P;
std::string First_name;
std::string Middle_name;
std::string Surname;
...
auto NAME = P.Name_Input(First_name, Middle_name, Surname);
std::cout << NAME << std::endl;
...
return 0;
}

最新更新