【发布时间】:2017-08-23 19:14:46
【问题描述】:
我是 C++ 的新手,我一直在尝试与其他问题不同的建议,但我无法让我的代码正常工作。
我有一个类“PChar”和另一个类“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;
};
“字符.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);
}
“main.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;
^
这是一个更大项目的一部分,这就是文件结构如此的原因,我只是简化了代码以重现错误。我已经尝试过其他类似问题的解决方案,但它们似乎不起作用。欢迎任何帮助或提示。谢谢!
【问题讨论】:
-
当你转发声明一个类时,你仍然需要在使用它之前包含提供它定义的标题。例如,您需要在“action.cpp”中包含“character.h”。
-
这个例子有严重的错误。
*subject=p1;不会做你想做的事。subject是一个未初始化的指针。取消引用是未定义的行为。至少,您需要分配一个新的PChar作为您的论点的副本。
标签: c++ circular-dependency incomplete-type