繁体   English   中英

获取类类型重新定义和其他一些错误

[英]Getting class type redefinition and a few other errors

我正在为一个项目创建一个学生数据管理控制台应用程序。 我创建了一个名为 Student 的类,它存储学生需要拥有的所有数据,并且它还具有与之关联的所有 getter 和 setter。 这是我所有文件的布局方式:

学生.h

#include <iostream>
#include <string>
using namespace std;


class Student {

private:
    string name;
    string id;
    string email;

    int presentation;
    int essay1;
    int essay2;
    int project;

public:
    //constructor
    //Student();
    //setters
    void set_name(string);
    void set_id(string);
    void set_email(string);
    void set_presentation(int);
    void set_essay1(int);
    void set_essay2(int);
    void set_project(int);
    //getters
    string get_name();
    string get_id();
    string get_email();
    int get_presentation();
    int get_essay1();
    int get_essay2();
    int get_project();
};

学生.cpp

#include <iostream>
#include <string>
#include "Student.h"
using namespace std;


//constructor definition
/*
Student::Student(void) {
    cout << "Student created" << endl;
}
*/

//setter definition
void Student::set_name(string s) {
    name = s;
}

void Student::set_id(string s) {
    id = s;
}

void Student::set_email(string s) {
    email = s;
}

void Student::set_presentation(int a) {
    presentation = a;
}

void Student::set_essay1(int a) {
    essay1 = a;
}

void Student::set_essay2(int a) {
    essay2 = a;
}

void Student::set_project(int a) {
    project = a;
}

//getter definition
string Student::get_name() {
    return name;
}

string Student::get_id() {
    return id;
}

string Student::get_email() {
    return email;
}

int Student::get_presentation() {
    return presentation;
}

int Student::get_essay1() {
    return essay1;
}

int Student::get_essay2() {
    return essay2;
}

int Student::get_project() {
    return project;
}

主程序

#include <iostream>
#include <string>
#include "Student.h"
using namespace std;


int main() {

    cout << "Hello World!" << endl;

    Student student1;
    Student student2;
    Student student3;

    student1.set_name("John");
    student2.set_name("Bob");
    student3.set_name("Carl");


    return 0;
}

当我尝试运行我的程序时,出现以下错误:

错误 1 ​​error C2011: 'Student' : 'class' 类型重新定义

错误 2 错误 C2079:'student1' 使用未定义的类 'Student'

错误 5 错误 C2228:'.set_name' 的左边必须有类/结构/联合

错误 9 错误 C2027:使用未定义的类型 'Student'

我该如何解决这个问题?

我很确定这是一个错误,因为student.h在某个.cpp文件中包含两次。 因此,您需要使用所谓的头文件保护来确保该文件在每个.cpp文件中只包含一次:

#ifndef STUDENT_H
#define STUDENT_H

#include <iostream>
#include <string>
using namespace std;

class Student {

/* ... */

};

#endif

这背后的想法是#include是一个预处理器指令,它导致参数文件被复制到发出#include的文件中。 因此,如果文件 A 和 B 包含Student.h ,而文件 C 包含文件 A 和 B,那么class Student的声明最终会重复。 因此错误。 上面的宏确保不会发生这种情况。

根据问题作者的评论进行编辑:

#pragma once#ifndef .. #define #endif但非标准相同。

看到#pragma once 还是包含守卫? 以供参考。

我有同样的错误。 我只是清理并重建解决方案并解决了错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM