简体   繁体   English

C ++静态成员变量

[英]C++ Static member variables

I have a class header: 我有一个类头:

class Game {
    static Game instance;
}

And I want to set the 'instance' to the "this" object on instantiation, but can't get it to work. 而且我想在实例化时将“实例”设置为“ this”对象,但无法使其正常工作。

Here's my implementation: 这是我的实现:

Game::Game() {
    Game::instance = this;
}

Visual Studio gives a red squiggly thing on the = 's operator saying: Visual Studio在=的运算符上给出了一个红色的蠕动内容:

Error: no operator "=" matches these operands
operands are types are: Game = Game *

Update 更新资料
I didn't understand the error but I tried changing the assignment code to this: 我不明白该错误,但尝试将分配代码更改为此:

Game::instance = * this;

And the error went away. 错误消失了。

So, now I'm wondering, what is the difference between those two assignment statements? 所以,现在我想知道,这两个assignment语句之间有什么区别?

I think II sort of know... but an explanation would be nice. 我想我有点知道...但是做个解释会很好。

Sounds like you're going for the singleton pattern! 听起来好像您要使用单例模式! Search it for some reading. 搜索它以阅读一些内容。 Some people don't like it and I've never had a use for it but if you want it then you'll need more of a framework than you have. 有些人不喜欢它,我从来没有使用过它,但是如果您想要它,那么您将需要比您更多的框架。 Note that this doesn't exist until you have created an object. 请注意, this并不存在,直到你已经创建了一个对象。 Also be careful, if you use =*this you will be making a copy. 同样要小心,如果使用=*this ,将进行复制。

If you want your instance to be available from the start of the program then you perhaps should just declare a global instance of the class, it's easier and safer. 如果您希望instance在程序开始时就可用,那么您也许应该只声明该类的全局实例,这样更容易,更安全。 The singleton pattern is for when you want delayed instantiation or optional instantiation of your class. 单例模式适用于您需要延迟实例化或类的可选实例化的情况。

Should be 应该

static Game* instance; // a pointer

Now instance points to the newly created instance. 现在, instance指向新创建的实例。

If you instead do this: 如果您改为这样做:

Game::instance = *this;

instance is assigned a 'snapshot' of the current state of the new object. instance被分配了新对象当前状态的“快照”。 This is probably not what you want. 这可能不是您想要的。

instance is an Object. instance是一个对象。 this is a pointer to your current Object. this是指向您当前对象的指针。 By using * this , you are dereferencing your pointer, hence returning the pointee (= the current object) 通过使用* this ,您将取消引用指针,因此返回pointee(=当前对象)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM