c++:私有构造函数意味着标头中没有该类对象的定义?
还有一个问题,你来吧!... 不管怎样,我有两个带有私有构造函数和静态函数的类来返回该类的实例。 一切都很好,我有一个 main.cpp 文件,我在其中设法获取了我的 gameState 对象指针,方法是:
gameState *state = gameState::Instance();
但现在我似乎遇到了问题。为了方便起见,我希望 gameState 实例和 actionHandler 实例都保留彼此的指针副本。所以我尝试包含在彼此的头文件中:
gameState *state;
然而
actionHandler *handler;
,这似乎不起作用......我得到“错误 C2143:语法错误:缺少 ';'这两行上的 '*'" 错误之前...如果某个类具有私有构造函数,您是否不能在标头中定义该类的变量?或者问题是别的什么? 或者可能是因为指向实例的指针存储为静态成员?
编辑:谢谢大家!这几天我学到的 C++ 知识量真是惊人……太棒了!
Yet another question, go me!...
Anyway, I have 2 classes with private constructors and static functions to return an instance of that class.
Everything was fine, I have a main.cpp file where I managed to get hold of my gameState object pointer, by doing:
gameState *state = gameState::Instance();
But now I seem to have a problem. For the sake of convenience, I wanted both the gameState instance and a actionHandler instance to retain a copy of the pointer to each other. So I tried to include in each other's header files:
gameState *state;
and
actionHandler *handler;
This however, doesn't seem to work... I get "error C2143: syntax error : missing ';' before '*'" errors on both of those lines... Can you not define variables of a certain classe's in the header if that class has a private constructor? Or is the problem something else?
OR maybe it is because the pointer to teh instance is stored as a static member?
EDIT: Thanks guys! It's amazing the amount of c++ knowledge I'm getting these last couple of days.. awsome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您需要将相反类的前向声明添加到每个类的头文件中。例如:
和:
It looks like you need to add a forward declaration of the opposite class to each class's header file. For example:
and:
不是因为私有构造函数。
这是因为你有循环依赖。因此,当您尝试编译类 A 时,您需要编译类 B,类 B 需要编译类 A,依此类推。
尝试前向声明。
在定义gameState的头文件中
Its not because the private constructor.
Its because you have a circular dependency. So when you try to compile class A, you need to compile class B, which needs compiled class A, and so on.
Try a forward declaration.
In the header file where gameState is defined
该问题与私有构造函数无关。在给定的翻译单元(.cpp 文件和所有包含的 .h 文件)中,C++ 编译器在声明类之前无法识别该类的标识符。当两个类包含相互引用的成员时,这会带来问题。该解决方案称为“前向声明”,即只有类名,但没有主体。在您的情况下,它可能看起来像这样:
== gameState.h ==
== actionHandler.h ==
The problem has nothing to do with the private constructors. In a given translation unit (.cpp file and all included .h files), the C++ compiler doesn't recognize the identifier for a class until the class is declared. This poses a problem when two classes contain members that refer to each other. The solution is called a "forward declaration", which is just the class name, but no body. It may look something like this in your case:
== gameState.h ==
== actionHandler.h ==