[英]I am new in programming. I keep getting an error message after compiling my code that contains a class definition included in a .h file
I am trying to call a member function of a custom class, but I keep getting error messages:我正在尝试调用自定义 class 的成员 function,但我不断收到错误消息:
expected primary-expression before First_name expected primary-expression before Middle_name expected primary-expression before Surname
This is the code for main cpp
:这是
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;
This is the header file:这是 header 文件:
class Person{
public:
std::string Name_Input(std::string First_name, std::string Middle_name, std::string Surname);
} ;
The header file compiles well, and has been link to a .cpp
file to define the method, and that section also works perfectly. header 文件编译良好,并已链接到
.cpp
文件来定义方法,该部分也可以完美运行。 My problem is with the main.cpp
file.我的问题是
main.cpp
文件。
Neither main.cpp
nor People.h
are defining std::string
, so the compiler doesn't know what it is. main.cpp
和People.h
都没有定义std::string
,所以编译器不知道它是什么。
You need to add #include <string>
to People.h
:您需要将
#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
A general rule of thumb is that any source file that needs to use a type defined in another source file should #include
that other file (except in cases where using forward declarations will suffice, such as when breaking circular references).一般的经验法则是,任何需要使用在另一个源文件中定义的类型的源文件都应该
#include
该其他文件(除非使用前向声明就足够了,例如在破坏循环引用时)。 SeeIs it good practice to rely on headers being included transitively?请参阅依赖传递包含标题的好习惯吗? .
. Which means that
main.cpp
should have an #include <string>
statement as well, even if People.h
(or any other header main.cpp
uses) already has its own #include <string>
statement.这意味着
main.cpp
也应该有一个#include <string>
语句,即使People.h
(或任何其他 header main.cpp
使用)已经有自己的#include <string>
语句。
Also, your use of std::string
in main()
is all wrong.此外,您在
main()
中使用std::string
都是错误的。 Don't include the type name when passing a variable to a function or class method.将变量传递给 function 或 class 方法时不要包含类型名称。 Use the type name only in the declaration of a variable or function parameter.
仅在变量或 function 参数的声明中使用类型名称。
Try this instead:试试这个:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.