C++ 将代码分离到头文件时出现问题
这个程序工作正常,但当我将“Class StudentsName”分离并将其放在头文件中时,它无法正常工作。我通过右键单击标题文件夹并选择新项目和标题,将标题文件添加到我的项目中,但它无法正常工作。请帮助我 主文件:C++ 将代码分离到头文件时出现问题,c++,header-files,name-lookup,using-directives,C++,Header Files,Name Lookup,Using Directives,这个程序工作正常,但当我将“Class StudentsName”分离并将其放在头文件中时,它无法正常工作。我通过右键单击标题文件夹并选择新项目和标题,将标题文件添加到我的项目中,但它无法正常工作。请帮助我 主文件: #include "iostream" #include "string" #include "Students.h" using namespace std; int main() { string nameO
#include "iostream"
#include "string"
#include "Students.h"
using namespace std;
int main()
{
string nameOfStudent;
StudentsName myStudentsName(" The student name is: Jason");
cout<<myStudentsName.getMyName()<<endl;
cout<<"please enter the name of the student: "<<endl;
getline(cin, nameOfStudent);
myStudentsName.setMyName(nameOfStudent);
cout<<endl;
myStudentsName.displayMyName();
system("pause");
return 0;
}
使用指令
using namespace std;
在包含标题“Student.h”之后放置
因此名称字符串
在标题“Students.h”
中未定义
将指令放在包含标题之前
#include "iostream"
#include "string"
using namespace std;
#include "Students.h"
虽然在标题
“Students.h”
中包含标题
和
,并使用限定名称(如std::string
)会更好,但真的没有更好的方法吗?比如,包括实际使用的标题?这只会使标题变得不可移植。提供一个不鼓励这种做法的答案不是更好吗?头文件不包含它使用的内容,这才是真正的问题所在。@sweenish,正如你所说的,“这个练习”实际上在所有初学者的书中都有使用。因此,当他在阅读这样一本书时,指出using指令必须放在哪里就足够了。至少,我会让它不被处理,并解决只在标题中包含
的实际问题。你是在看我的历史还是什么?我肯定我说过,但这也不等同于我提倡它,当然不是现在。@Vlad我希望你不介意我以任何方式愚弄了这个问题。
using namespace std;
#include "iostream"
#include "string"
#include "Students.h"
using namespace std;
#include "iostream"
#include "string"
using namespace std;
#include "Students.h"