0

如何正确引用两个对象(双重链接的子对象和父对象)中的子对象和父对象?这样做时,我得到一个编译错误:**** does not name a type. 我怀疑这与由于#define 标签而被省略的#include 语句有关。因此应该如何包含这些标签?

三个文件(Parent.h、Child.h、main.cpp)是这样写的:

    /* Parent.h */
#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

#include "Child.h"

class Parent {
public:
    Parent() {}
    ~Parent() {}
    void do_parent(Child* arg);
};
#endif

/* Child.h */
#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

#include "Parent.h"

class Child {
public:
    Child() {}
    ~Child() {}
    void do_child(Parent* arg);
};
#endif

/* main.cpp */
#include "child.h"
#include "parent.h"

int main()
{
    Child   a();
    Parent  b();
    a.do_parent(Child& arg);
    return 0;
}
4

5 回答 5

1

您有头文件的循环依赖。只需在其中一个标头中前向声明任一类即可。例如:

    /* Parent.h */
#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

//#include "Child.h"   ----> Remove it
class Child;           //Forward declare it

class Parent {
public:
    Parent() {}
    ~Parent() {}
    void do_parent(Child* arg);
};
#endif
于 2013-02-11T09:00:39.970 回答
1

使用类原型/前向声明:

class Child;

class Parent;

在彼此的类声明之前并删除包含。

于 2013-02-11T09:01:07.683 回答
1

您定义了两个函数而不是对象,请参阅最令人烦恼的解析

更新

Child   a();              // a is a function returns Child object
Parent  b();              // b is a function returns Parent object
a.do_parent(Child& arg);

Child   a;           // a is a Child object
Parent  b;           // b is a Parent object
b.do_parent(&a);

此外,您有循环包含问题,要打破循环包含,您需要转发一种类型:

孩子.h

#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

//#include "Parent.h"  Don't include Parent.h
class Parent;           // forward declaration
class Child {
public:
    Child() {}
    ~Child() {}
    void do_child(Parent* arg);
};
#endif

孩子.cpp

#include "Parent.h"
// blah
于 2013-02-11T09:02:06.700 回答
0

这个错误(在询问编译/链接器错误时,您应该始终包含完整未经编辑的错误消息),是这一行:

a.do_parent(Child& arg);

您应该在这里传递一个指向Child对象的指针,而不是变量声明:

b.do_parent(&a);
于 2013-02-11T09:01:42.163 回答
0

您需要对 or 进行前向声明。尝试修改您的文件之一。class Parentclass Child

在你的 Parent.h 中:

#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

class Child;     // Forward declaration of class Child

class Parent {
public:
    Parent() {}
    ~Parent() {}
    void do_parent(Child* arg);
};
#endif

或在您的 Child.h 中:

#pragma once
#ifndef _CHILD_CLS
#define _CHILD_CLS

class Parent;    // Forward declaration of class Parent

class Child {
public:
    Child() {}
    ~Child() {}
    void do_child(Parent* arg);
};
#endif

这个问题应该对你有很大帮助。

于 2013-02-11T09:02:42.230 回答