C ++无效使用不完整类型

时间:2016-03-04 11:51:05

标签: c++ class

我有以下文件:main.cpp,class.cpp,class.hpp,student.cpp,student.hpp

以下是代码:

main.cpp中:

#include <iostream>
#include <vector>
#include <string>

#include "class.hpp"


using namespace std;


int main(){
    vector<Student> students;
    vector<Class> classes;

    Class B4( 4, 'B' );
    classes.push_back( B4 );

    Student john( "John", "Boss", B4 );
    students.push_back( john );
    Student marc( "Marc", "Solo", B4 );
    students.push_back( marc );

    marc.printInfo();
    B4.addStudent( marc );

    return 0;
}

class.hpp:

#include <vector>
#include "student.hpp"

using namespace std;

class Class{
private:
    int number;
    char letter;
    vector<Student> students;

public:
    Class( int, char );

    void addStudent( Student & );
    void printClass();
};

class.cpp:

#include <iostream>
#include "class.hpp"


Class::Class( int number, char letter ){
    this -> number = number;
    this -> letter = letter;
}


void Class::printClass(){
    cout << this -> number << "." << this -> letter << endl;
}


void Class::addStudent( Student & student ){
    this -> students . push_back( student );
}

student.hpp:

#include <string>

using namespace std;

class Class;

class Student{
private:    
    string name;
    string surname;
    Class* classStudent;

public:
    Student( string name, string surname, Class & );

    void printInfo();
};

student.cpp:

#include <iostream>
#include "student.hpp"

using namespace std;

Student::Student( string name, string surname, Class & classStudent ){
    this -> name            = name;
    this -> surname         = surname;
    this -> classStudent    = &classStudent;
}

// printInfo
void Student::printInfo(){
    cout << "Name: " << this -> name << "\nSurname: " << this -> surname <<
                    "\nClass:" << this -> classStudent -> printClass() << endl;
}

当我编译这些文件时,我收到以下错误:

student.cpp: In member function ‘void Student::printInfo()’:
student.cpp:15:41: error: invalid use of incomplete type ‘class Class’
      "\nClass:" << this -> classStudent -> printClass() << endl;
                                         ^
In file included from student.cpp:2:0:
student.hpp:5:7: error: forward declaration of ‘class Class’
 class Class;
       ^

我从未遇到过这样的情况:我需要在第二课中使用第一堂课,在第一堂课中使用第二堂课。

1 个答案:

答案 0 :(得分:3)

添加

 #include "class.hpp"

#include <iostream>
#include "student.hpp"
student.cpp中的

,或者编译器不知道Class是什么。