简体   繁体   English

前向声明“ struct bb”,类

[英]forward declaration of ‘struct bb’, classes

I almost solved issues with my code with the help of stackoverflow users but now have different problem. 在stackoverflow用户的帮助下,我几乎用代码解决了问题,但现在遇到了其他问题。 My code now looks like this: 我的代码现在看起来像这样:

#include <iostream>
#include <cmath>
#include <sstream>
using namespace std;

class root
{
public:
    virtual ~root() {}

    virtual root* addA(const root& a) const=0;
    virtual root* addB(const root& b) const=0;
};

class bb;

class aa: public root
{
public:
    aa() { }
    aa(const aa& a) { }

    root* addA(const root& a) const
    {
        return new aa();
    }

    root* addB(const root& b) const
    {
        return new bb();
    }
};

class bb: public root
{
public:
    bb() { }
    bb(const bb& b) { }

    root* addA(const root& a) const
    {
        return new aa();
    }

    root* addB(const root& b) const
    {
        return new bb();
    }
};

int main(int argc, char **argv)
{
}

But when I compile it, it gives errors: 但是当我编译它时,会出现错误:

/home/brain/Desktop/Temp/Untitled2.cpp||In member function ‘virtual root* aa::addB(const root&) const’:|
/home/brain/Desktop/Temp/Untitled2.cpp|30|error: invalid use of incomplete type ‘struct bb’|
/home/brain/Desktop/Temp/Untitled2.cpp|15|error: forward declaration of ‘struct bb’|
||=== Build finished: 2 errors, 0 warnings ===|

For this specific case, you can move the definitions of the member function to after class bb has been defined. 对于这种特定情况,可以将成员函数的定义移动到定义了bb类之后。 OR preferably put them in a separate .cpp file and include the header. 或者最好将它们放在单独的.cpp文件中,并include标题。

class aa: public root
{
public:
    // ....
    root* addB(const root& b) const;
    // Declaration only
};


class bb: public root
{
public:
    // ....
};

// Here.
inline    // <--- If you define it in the header.
root* aa::addB(const root& b) const
{
    return new bb();
}

Since compiler doesn't have any idea about class bb so it wont be able to create an object and return it return bb() 由于编译器对bb类没有任何了解,因此它将无法创建对象并将其return bb()

It will work if you define the root* addB(const root& b) const outside the class, because at that time it would be able to know the size of class bb . 如果您在类之外定义root* addB(const root& b) const将会起作用,因为那时它可以知道bb的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM