2016-03-04 64 views
-1

我有以下文件:main.cpp中,class.cpp,class.hpp,student.cpp,student.hppC++中使用无效不完全型的

下面是代码:

的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; 
    ^

我从来没有来像这样的情况:我需要在第二节课中使用第一节课,在第一节节中使用第二节课。

回答

3

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

添加

#include "class.hpp" 

student.cpp,或编译器将不知道什么Class是。

+0

我已经完成了完全相同的事情,我现在再试一次,当你刚发布这个答案时,g ++现在发布了一些奇怪的东西。就像重新定义类等等。其中有很多,我甚至不能在这里复制 – alik33

+0

@ alik33一旦你包含“class.h”,你还必须关心你的链接。 – dragosht

+1

@ alik33:发布* first *错误消息。一旦你解决了这个问题,其余的问题可能会消失(或者很明显如何解决)。 2:0, 从student.cpp:3: student.hpp: –

相关问题