1

我想保留指向另一个类的指针(或引用)。它可能是一个包含指向基类的指针矩阵的类,我希望能够在具有指向它的指针(或引用)的类的函数中使用该类的公共函数。假设它看起来像这样:

基础.h

#pragma once

class base
{
protected:
    int x;
    int y;
public:
    void setX (int _x)
    {
        x=_x;
    }
    void setY (int _y)
    {
        y=_y;
    }
    virtual void f ()=0;
};

派生的.h

#pragma once
#include "base.h"
#include "container.h"

class derived : public base
{
private:
    container* c;
public:
    derived (container* c, int x, int y)
        : c(c)
    {
        setX(x);
        setY(y);
    }

    void g ()
    {
        c->doStuff();
    }

    virtual void f ()
    {
        std::cout<<"f"<<std::endl;
    }
};

容器.h

 #pragma once
 #include "base.h"
 #include "derived.h"

 class container
 {
 private:
    base*** mat;
 public:
    container ()
    {
        mat=new base**[10];
        for (int i=0; i<10; ++i)
            mat[i]=new base*[10];

        for (int i=0; i<10; ++i)
            for (int j=0; j<10; ++i)
                mat[i][j]=NULL;

        mat[5][5]=new derived(this, 1, 2);
     }

    void doStuff ()
    {
        std::cout<<"stuff"<<std::endl;
    }
 };

我不断收到这些错误

derived.h(8): error     C2143: syntax error : missing ';' before '*'
derived.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
derived.h(10): error C2061: syntax error : identifier 'container'
derived.h(10): error C2065: 'c' : undeclared identifier
derived.h(12): error C2614: 'derived' : illegal member initialization: 'c' is not a base or member
derived.h(19): error C2065: 'c' : undeclared identifier
derived.h(19): error C2227: left of '->doStuff' must point to class/struct/union/generic type
1>          type is ''unknown-type''
container.h(20): error C2661: 'derived::derived' : no overloaded function takes 3 arguments

我知道我遗漏了一些东西,但我无法确定它是什么

4

1 回答 1

12

container.h您在和之间有一个循环包含依赖关系derived.h。幸运的是,它可以避免,因为derived不需要完整的定义container,所以您可以使用前向声明而不是包含:

#ifndef DERIVED_H_
#define DERIVED_H_
#include "base.h"

class container; // fwd declaration

class derived : public base
{
private:
    container* c;

//... as before

#endif

您将需要#include "container.h"derived.

作为一般规则,您应该包含所有需要包含的内容,仅此而已。

于 2013-09-04T13:15:34.130 回答