簡體   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