声明对象时,如何在C 中修复C2065错误
How can I fix the C2065 error in C ++ when declaring an object?
我不久前从Java更改为C 。一旦我尝试编码一些复杂的功能,我就会失败。我想制作一个指向我班级实例的变量。但是即使我尝试声明实例,我也会收到此错误...
#include <iostream>
#include "Game.h"
#include <string>
Game instance; // that should be the Instance
class Game
{
public:
Game()
{
instance = this; // here I got the error.
}
在C 中,与Java不同,当您写作:
Game instance; // that should be the Instance
您正在创建类型Game
的实际对象。在Java中,这将创建一个句柄变量,然后您需要使用new
操作员实际创建Game
对象。这不是它在C 中工作的方式。
在源线中:
Game()
{
instance = this; // here I got the error.
}
变量this
实际上是指向当前对象的指针。但是,instance
不是指针变量,它将由Game *instance;
定义,而是实际的Game
对象。将指针值分配给不是指针的东西是编译错误。
对您的来源的一种修改可能是您实际想要的也可能不是您想要的,就是进行以下更改:
#include <iostream>
#include "Game.h"
#include <string>
Game *instance; // global that contains a pointer to a Game object, no object created.
class Game
{
public:
Game()
{
instance = this; // we are creating an object of class Game now assign it to our global.
}
}
但是,这在C 中并没有意义。对于多个Game
对象,可以将构造函数多次调用。
假设标题文件game.h包含类定义,如果您只想创建一个Game
的实例,那么最直接的是将其写入:
#include <iostream>
#include "Game.h"
#include <string>
Game instance; // the global Game object that is created as part of the application starting up.
但是,如果您想使用Singleton Design模式创建一个实例,该模式将强制执行一个且仅创建一个对象,则需要进行其他工作,这需要更多涉及C 和类的知识构建。
您应该将实例声明为游戏指针:
Game *instance = NULL;
问题的原因是'this'是C 中的指针,而不是对对象的引用,因此您必须将其分配给对象:
instance = *this;
谨慎,尽管这将复制您的对象。尽管这就是您可以做到这一点的方法,但我想说的是,它不鼓励使用全球变量和一般的单例。我宁愿您建议您使用静态课程。有关此外观的讨论。总结:如果不需要,请不要使用单身。
相关文章:
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 错误: C2065: "QTcpSocket" : 未声明的标识符
- 无法解决 C2660 和 C2065 错误
- 声明对象时,如何在C 中修复C2065错误
- C 如何从构造函数中声明(错误C2065未宣布的标识符)
- 使用“rdtsc”:错误 C2065
- 错误 C2065:'lO':用于声明向量值的未声明标识符?
- 错误 C2065:"i":未声明的标识符
- C++ 错误 C2065:未声明的标识符
- 定义中未声明的标识符错误 C2065,显然存在
- 错误 C2065:"resultImgs":未声明的标识符
- 错误 C2065:模板函数中未声明的标识符
- 错误 C2065:'ID_MUTATE_GROUP':未声明的标识符
- 外部库中出现奇怪的C2065错误
- 错误 C2065:'ID_MUTATE_GROUP':未声明的标识符
- C++错误代码 C2065:"<类名>"未声明的标识符,即使它应该在另一个 .h 文件中声明
- 使用两个MFC项目时出现错误C2065
- 错误: C2065: 'DBL_MAX':未声明的标识符(在 VS2008 中,但在 VS2010 中未)
- 视觉C++错误 C2065 未声明的标识符
- 类中的向量.C2065错误