簡體   English   中英

前向聲明“ struct bb”,類

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

在stackoverflow用戶的幫助下,我幾乎用代碼解決了問題,但現在遇到了其他問題。 我的代碼現在看起來像這樣:

#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)
{
}

但是當我編譯它時,會出現錯誤:

/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 ===|

對於這種特定情況,可以將成員函數的定義移動到定義了bb類之后。 或者最好將它們放在單獨的.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();
}

由於編譯器對bb類沒有任何了解,因此它將無法創建對象並將其return bb()

如果您在類之外定義root* addB(const root& b) const將會起作用,因為那時它可以知道bb的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM