"invalid use of incomplete type" .解决循环依赖关系



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

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

"动作.h":

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

#endif

"行动.cpp":

#include "action.h"
Action::Action(){};
Action::Action(PChar& p1,PChar& p2)
{
*subject=p1;
*object=p2;
};

"字符.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    

"性格.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);
}

"主.cpp">

#include "action.h"
#include "character.h"
int main()
{
PChar char1("Joe");
PChar char2("Matt");
Action handshake;
char1.act(char2, 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;
^

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

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

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

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

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

当您取消引用未初始化的指针时。您需要使它们指向某个地方,可能您打算分配动态内存。在这种情况下,std::unique_ptr可以解决 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) )
{
}

当你无意修改对象时,你最好把它作为常量引用传递。

最新更新