1

我试图通过基类的另一个函数向基类的函数发送派生指针,但由于某种原因,它抱怨:错误:第 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;
}

你知道我怎么能解决这个问题吗?

4

2 回答 2

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);}
于 2013-09-20T16:12:27.717 回答
0

唯一的方法是将函数定义从类声明中取出,并将它们放在Derived. 在您尝试使用它们时,糟糕的编译器甚至还不知道存在哪些方法Derived

于 2013-09-20T16:04:03.210 回答