-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;
^
我從來沒有來像這樣的情況:我需要在第二節課中使用第一節課,在第一節節中使用第二節課。
我已經完成了完全相同的事情,我現在再試一次,當你剛發佈這個答案時,g ++現在發佈了一些奇怪的東西。就像重新定義類等等。其中有很多,我甚至不能在這裏複製 – alik33
@ alik33一旦你包含「class.h」,你還必須關心你的鏈接。 – dragosht
@ alik33:發佈* first *錯誤消息。一旦你解決了這個問題,其餘的問題可能會消失(或者很明顯如何解決)。 2:0, 從student.cpp:3: student.hpp: –