类中的函数不能更改类中的变量(C++)[关闭]

问题描述 投票:0回答:0

我有一个带有函数的类。在函数中,变量

ObjectCount
被更改。问题是变量没有被保存,所以当我再次调用该函数时,
ObjectCount
再次为 0.

班级:

#pragma once

#include "../main.h"

using namespace std;

class singleEnvironment {
    public:
        /* Variables */
        const char* Name;
        int index;
        singleObject Objects[256];
        int ObjectCount;

        /* Functions */
        void AddObject(const char* Name, ObjectTypes ObjectType){
            Objects[ObjectCount].ObjectType = ObjectType;
            Objects[ObjectCount].Name = Name;
            Objects[ObjectCount].index = ObjectCount;
            ObjectCount++;
            cout << ObjectCount << endl;
        }

        singleObject GetObjectbyName(const char* Name){
            for(int i=0; i<ObjectCount; i++){
                if(Objects[i].Name == Name) return Objects[i];
            }
        }
};

class Environments {
    public:
        /* Variables */
        singleEnvironment Environments[256];
        int EnvironmentCount;

        /* Functions */
        void CreateNewEnvironment(const char* Name){
            Environments[EnvironmentCount].Name = Name;
            Environments[EnvironmentCount].index = EnvironmentCount;
            EnvironmentCount++;
        }

        singleEnvironment GetEnvironmentByName(const char* Name){
            for(int i=0; i<EnvironmentCount; i++){
                if(Environments[i].Name == Name) return Environments[i];
            }
        }

        singleEnvironment GetEnvironmentByIndex(int Index){
            return Environments[Index];
        }
};

extern Environments Environment;

项目等级:

#pragma once

#include "../main.h"

using namespace std;

enum ObjectTypes {
    Empty,
    Sprite
};

class singleObject {
    public:
        const char* Name;
        int index;
        ObjectTypes ObjectType;
        Properties ObjectProperties;
};

每当我调用

AddObject()
,我想增加
ObjectCount
,但它在函数内部递增,但在函数之后没有被保存。我不知道为什么。

编辑: 在 Environments 类中,变量 EnvironmentCount 工作得很好,在 singleEnvironment 中它基本相同,但它不起作用

有关更多代码,请查看 GitHub 存储库:https://github.com/Mad-Mushroom/MadEngine/tree/main/Mad2D/src 在environment/environment.h

c++ function class variables
© www.soinside.com 2019 - 2024. All rights reserved.