1

別のクラスへのポインター (または参照) を保持したい。それは、基本クラスへのポインターのマトリックスを含むクラスである可能性があり、そのクラスへのポインター (または参照) を持つクラスの関数内でそのクラスのパブリック関数を使用できるようにしたいと考えています。次のように見えるとしましょう。

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

派生.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 に答える