我想保留一个指向另一个类的指针(或引用)。它可能是一个包含指向基类的指针矩阵的类,并且我希望能够在具有指向它的指针(或引用)的类的函数内使用该类的公共函数。假设它看起来像这样:
基数
#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;
};
派生
#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
我知道我缺少什么,我只是无法查明它是什么
您container.h
和之间有一个循环包含依赖关系derived.h
。幸运的是,由于derived
不需要的完整定义container
,因此可以避免这种情况,因此可以使用前向声明代替include:
#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
。
通常,您应该包括所有需要包括的内容,仅此而已。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句