我从模板类继承。当我进入教师班时,我想进入学科班,反之亦然。我收到一个错误 Invalid use of incomplete type struct Subect;
void addSubject(Subject *s) {
this->addReference(s);
s->addReference(this); when I comment this line the it compiles without errors, but I cannot insert into Subject
}
我的整个代码如下
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class Subject;
template <class T>
class abstractReference {
vector<T*> list;
public:
string code;
void addReference( T*);
void delReference( T*);
bool hasReference( T*);
T * getReference(int );
};
template <class T>
void abstractReference<T>::addReference(T* ref) {
list.push_back(ref);
//ref->addReference(this);
}
template <class T>
void abstractReference<T>::delReference(T* ref) {
int i;
for (i=0; i<list.size(); i++) {
if (list[i]== ref) list.erase(i);
}
}
template <class T>
bool abstractReference<T>::hasReference( T* ref) {
if (list.size() == 0) return false;
int i;
for (i=0; i<list.size(); i++) {
if (list[i] == ref) return true;
}
return false;
}
template <class T>
T* abstractReference<T>::getReference(int i) {
if (i < 0 || i > list.size()) return NULL;
return list[i];
}
class Teacher : public abstractReference<Subject> {
string fname;
string lname;
float sal;
public:
Teacher(string c, string fn, string ln, float s): fname(fn), lname(ln), sal(s) {
}
Teacher() {sal =0; fname=""; lname="";}
void setInfo(string c, string fn, string ln, float s=0.00) {
code=c;
fname = fn;
lname = ln;
sal = s;
}
string getName() {
return fname + " " + lname;
}
float getSal() {
return sal;
}
void addSubject(Subject *s) {
this->addReference(s);
s->addReference(this);
}
void delSubject(Subject *s) {
}
};
class Subject : public abstractReference<Teacher> {
string title;
public:
Subject(string c=NULL, string t=NULL) {
title = t;
}
string getTitle() {
return title;
}
};
main() {
Teacher *t;
t = new Teacher("J109", "Dexter", "McConnell",15000);
Subject *s, *s1, *s2;
s= new Subject("E001", "English");
s1= new Subject("M001", "Maths");
s2= new Subject("s001", "Science");
t->addSubject(s);
t->addSubject(s1);
cout << "Has Reference " << t->hasReference(s2) << endl;
cout << "Done..." << endl;
cout << t->getReference(1)->getTitle() << endl;
}