C++ C++;将派生指针作为参数发送
我试图通过基类的另一个函数发送指向基类函数的派生指针,但由于某些原因,它会抱怨: 错误:第8行上的不完整类型“struct-Derived”的使用无效C++ C++;将派生指针作为参数发送,c++,function,class,pointers,derived,C++,Function,Class,Pointers,Derived,我试图通过基类的另一个函数发送指向基类函数的派生指针,但由于某些原因,它会抱怨: 错误:第8行上的不完整类型“struct-Derived”的使用无效 #include <iostream> using namespace std; class Derived; class Base { public: void getsomething(Derived *derived){derived->saysomething();} //This is 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;
}
#包括
使用名称空间std;
类派生;
阶级基础
{
公众:
void getsomething(派生的*派生的){Derived->saysomething();}//这是第8行
void receiveIt(派生的*派生的){getsomething(&*派生的);}
};
派生类:公共基
{
公众:
void giveself(){receiveit(this);};
空话{cout唯一的方法是将函数定义从类声明中取出,并将它们放在派生的
声明之后。在您试图使用它们的时候,糟糕的编译器甚至还不知道派生的
上存在哪些方法。唯一的方法是将函数定义从类声明中取出在您试图使用它们的时候,糟糕的编译器甚至还不知道在派生的上存在什么方法。当编译器需要有关类成员的信息时,您不能使用前向声明
转发声明仅在告诉编译器具有该名称的类确实存在并且将在以后声明和定义时有用
因此,请您喜欢以下内容:
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);}
类派生;
阶级基础
{
公众:
void getsomething(派生的*派生的);
无效接收(派生*派生);
};
派生类:公共基
{
公众:
void giveself(){receiveit(this);};
void saysomething(){cout当编译器需要有关类成员的信息时,不能使用前向声明
转发声明仅在告诉编译器具有该名称的类确实存在并且将在以后声明和定义时有用
因此,请您喜欢以下内容:
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);}
类派生;
阶级基础
{
公众:
void getsomething(派生的*派生的);
无效接收(派生*派生);
};
派生类:公共基
{
公众:
void giveself(){receiveit(this);};
void saysomething(){cout为什么基类知道派生类?@soon是对的;这是可以实现的,但让基类知道派生类通常是一个不好的设计想法。也许实现这一点的更好方法是使getsomething()
一个虚拟函数。receiveit
函数似乎非常无用,因为它只是用一个模糊的参数derived
调用getsomething
。为什么基类知道派生类?@很快是正确的;这可以实现,但让基类知道派生类通常是一个糟糕的设计思想可能更好的实现方法是将getsomething()
设为虚拟函数。此外,receiveit
函数似乎毫无用处,因为它只是使用模糊参数派生的调用getsomething
。