【问题标题】:Classes on different files , how to make it work? [duplicate]不同文件上的类,如何使其工作? [复制]
【发布时间】:2018-05-07 19:57:37
【问题描述】:

我的问题是如何将类放在不同的文件中并使程序运行?当我尝试在 Student.h 文件中构建和运行它时出现错误 ---> 字符串没有命名类型

main.cpp:

#include <iostream>
#include "Student.h"

using namespace std;

int main()
{
    Student *a;

    a = new Student(1,"Astudent");
    a->printStudent();

    system("PAUSE");
    return 0;
}

学生.h:

#ifndef STUDENT_H
#define STUDENT_H

class Student
{
    private:
        int id;
        string name;

    public:
        Student(int id,string name);
        void printStudent();
};

#endif

学生.cpp:

#include <iostream>
#include "Student.h"

using namespace std;

Student::Student(int id,string name)
{
    this->id = id;
    this->name = name;
}

Student::printStudent()
{
    cout << id << "." << name << endl;
}

【问题讨论】:

  • 您没有在头文件中包含任何包含...
  • 您如何尝试构建和运行它?

标签: c++


【解决方案1】:

Student.h 需要包含字符串才能使用string 作为类型。例如:

#include <string>

【讨论】:

  • 谢谢,很简单,我还需要在 .cpp 文件中输入 ---> void Student::printStudent() 而不是 ---> Student::printStudent()
  • 不是最优雅的解决方案,但完全可以接受。我更喜欢将其声明为std::string name,或者即使这不是一个好习惯,也可以将using namespace std 放在.h
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 2018-05-26
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多