我继承自模板类。当我进入教师类(class)时,我想进入学科类(class),反之亦然。 我收到错误 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;
}
最佳答案
问题是编译器不理解类型Subject
,你可能前向声明它或者忘记包含定义它的头文件。
结果是,对于编译器来说,Subject
是一个不完整类型,它无法执行任何需要了解 Subject
布局的操作,调用它的成员函数就是这样一个例子。
解决方法是:
您应该在源 cpp 文件中包含定义 Subject
的头文件,您在其中定义了以下内容:
void addSubject(Subject *s)
如果您没有多个文件,请确保类 Subject
已定义之前 您已定义函数 addSubject()
.
关于c++ - 错误 : Invalid use of incomplete type struct Subject; error: forward declaration of struct Subject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10275436/