保持指向另一个类的指针

时间:2013-09-04 13:13:00

标签: c++

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

base.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;
};

derived.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;
    }
};

container.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

我知道我错过了一些东西而且我无法确定它是什么

1 个答案:

答案 0 :(得分:12)

container.hderived.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

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