我试图通过另一个Base类的函数向基类的函数发送派生指针,但由于某种原因,它抱怨: 错误:在第8行无效使用不完整类型'struct Derived'。
#include <iostream>
using namespace std;
class Derived;
class Base
{
public:
void getsomething(Derived *derived){derived->saysomething();} //This is line 8
void recieveit(Derived *derived){getsomething(&*derived);}
};
class Derived : public Base
{
public:
void giveself(){recieveit(this);};
void saysomething(){cout << "something" << endl;}
};
int main()
{
Base *b = new Base;
Derived *d = new Derived;
d->giveself();
return 0;
}
你知道我怎么解决这个问题吗?
答案 0 :(得分:1)
当编译器需要有关类成员的信息时,不能使用前向声明。
前向声明仅用于告诉编译器具有该名称的类确实存在并且稍后将被声明和定义。
如下所示:
class Derived ;
class Base
{
public:
void getsomething(Derived *derived);
void recieveit(Derived *derived);
};
class Derived : public Base
{
public:
void giveself(){recieveit(this);};
void saysomething(){cout << "something" << endl;}
};
void Base::getsomething(Derived *derived){derived->saysomething();}
void Base::recieveit(Derived *derived){getsomething(&*derived);}
答案 1 :(得分:0)
唯一的方法是从类声明中取出函数定义,并在声明Derived
之后放置它们。在您尝试使用它们时,可怜的编译器甚至不知道Derived
上存在哪些方法。