声明对象时,如何在C 中修复C2065错误

How can I fix the C2065 error in C ++ when declaring an object?

本文关键字:C2065 错误 对象 声明      更新时间:2023-10-16

我不久前从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;

谨慎,尽管这将复制您的对象。尽管这就是您可以做到这一点的方法,但我想说的是,它不鼓励使用全球变量和一般的单例。我宁愿您建议您使用静态课程。有关此外观的讨论。总结:如果不需要,请不要使用单身。