"invalid use of incomplete type"。解决循环依赖

"invalid use of incomplete type". Solving circular dependencies

我是 C++ 的新手,我一直在尝试其他问题的不同建议,但我无法使我的代码工作。

我有一个 class "PChar" 和另一个 class "Action"。一个 Action 有两个 PChar 成员,PChar ("act()") 的一个方法必须能够创建一个 Action 对象。所以在尝试了不同的东西之后我得到了这个代码:

"action.h":

#ifndef ACTION_H
#define ACTION_H

class PChar;

class Action
{
    PChar *subject, *object;
public:
    Action();
    Action(PChar& p1, PChar& p2);
};


#endif

"action.cpp":

#include "action.h"

Action::Action(){};

Action::Action(PChar& p1,PChar& p2)
{
    *subject=p1;
    *object=p2;
};

"character.h"

#ifndef CHARACTER_H
#define CHARACTER_H

#include <string>

#include "action.h"

class PChar
{
public:
    std::string name;

    PChar();

    PChar(std::string input_name);

    void act(PChar& target, Action &action);
};
#endif    

"character.cpp"

#include "character.h"

PChar::PChar(){}

PChar::PChar(std::string input_name)
{
    name=input_name;
}

void PChar::act(PChar& target, Action& action)
{
    action=Action(*this, target);
}

"main.cpp"

#include "action.h"
#include "character.h"

int main()
{
    PChar char1("Joe");
    PChar char2("Matt");
    Action handshake;
    char1.act(char2, handshake);
}

目标是创建一个对象 "handshake",其中包含两个角色作为成员。编译时出现错误:

action.cpp:7:10: error: invalid use of incomplete type ‘class PChar’
  *subject=p1;
          ^
In file included from action.cpp:1:0:
action.h:4:7: note: forward declaration of ‘class PChar’
 class PChar;
       ^
action.cpp:8:9: error: invalid use of incomplete type ‘class PChar’
  *object=p2;
         ^
In file included from action.cpp:1:0:
action.h:4:7: note: forward declaration of ‘class PChar’
 class PChar;
       ^

这是一个更大项目的一部分,这就是文件结构如此的原因,我只是简化了代码以重现错误。我尝试过其他类似问题的解决方案,但它们似乎不起作用。欢迎任何帮助或提示。谢谢!

您可以转发声明类型来声明指向它的指针或引用。但是当您开始使用该类型(将其声明为值或分配给它或调用方法)时,必须对其进行定义。在 action.cpp 中包含 character.h 将解决编译错误。请注意,您的 ctor 中有 UB:

Action::Action(PChar& p1,PChar& p2)
{
    *subject=p1;
    *object=p2;
}

当您取消引用未初始化的指针时。您需要让它们指向某处,可能您打算分配动态内存。在那种情况下 std::unique_ptr 会更可取,因为 Rule of 3/5/0:

会解决问题
class Action
{
    std::unique_ptr<PChar> subject, object;
public:
    ...
};

Action::Action(const PChar& p1, const PChar& p2) :
    subject( new PChar(p1) ), object( new PChar(p2) )
{
}

当您不打算修改对象时,最好将其作为常量引用传递。

C++ 需要知道类型的详细信息才能进行编译和赋值操作。

一个解决方案是在 "Action.cpp" 中也包含 "Character.h"