문제

I am trying to send a derived pointer to a base class's function through another one of the Base class's functions, but for some reason, it complains: error: invalid use of incomplete type 'struct Derived' on line 8.

#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;
}

do you know how I could fix this?

도움이 되었습니까?

해결책

You can't use forward declaration, when the compiler needs information about the class's members.

A forward declaration is only useful for telling the compiler that a class with that name does exist and will be declared and defined later.

So do like following :

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);}

다른 팁

The only way is to take the function definitions out of the class declaration and put them after the declaration of Derived. At the point you're trying to use them, the poor compiler doesn't even know what methods exist on Derived yet.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top