c++ - 类在同一内存位置创建另一个类的多个对象 (C++)

标签 c++

所以,我得到了包含另一个类的 vector 的此类。每当我尝试将一个新对象插入此 vector 时,它每次都会在相同的内存位置创建该对象。

(希望)相关代码:

class FSM{
    private:
        std::vector<Node> nodeList;
        int cap;
        int obs;
        int topNode;

    public:
        FSM(int nodeCap, int numObs){
            cap = nodeCap;
            obs = numObs;
            topNode = -1;
        }

        bool addNode(){
            if (isFull()) return false;
            nodeList.push_back(Node(obs));
            topNode++;
            return true;
        }

现在,如果我在主函数中创建一个独立的 Node 对象并计算 &node,我将获得不同的内存位置。但是在 FSM 类中创建的总是相同的。此外,如果我更改 FSM 类存储的其中一个节点中的任何内容,它会为所有节点更改它。我不知道发生了什么。

编辑:根据要求,这里是 Node 类。只想发布整个内容,不确定相关内容。

class Node{
    private:
        std::vector<int> connects;
        int action;

    public:
        Node(int numObs){
            for(int i = 0; i < numObs; i++){
                connects.push_back(-1);
            }
            srand(time(NULL));
        }

        void setConnections(std::vector<int> newVec){
            for (int i = 0; i < connects.size(); i++){
                connects[i] = newVec[i];
            }
        }

        int getConnection(int index){
            return connects[index];
        }

        std::vector<int> getConnectionList(){
            return connects;
        }

        void setAction(int act){
            action = act;
        }

        int getAction(){
            return action;
        }

        void setRandomConnections(int numNodes){
            for (int i = 0; i < connects.size(); i++){
                connects[i] = rand() % numNodes;
            }
        }
};

编辑第二个:这是我的主要工作。

int main(){
FSM myFSM(5, 3);
while (!myFSM.isFull()){
    myFSM.addNode();
    std::cout << &myFSM.getTopNode(); // getTopNode() returns the most recent
                                              // node.
}
}

最佳答案

如果 getTopNode 做了我认为它做的事情,那么您正在打印一个临时对象的地址(也就是顶级节点的拷贝,而不是顶级节点本身)。所以那个代码是没有意义的。

Here我已经为 FSM 中的节点位置实现了打印功能:

void printNodeLocations()
{
    for(Node& n : nodeList) { std::cout << &n << std::endl; }
}

我得到了不同的预期:

0x8ad3018
0x8ad301c

编辑:我无法重现您关于更改一个节点会更改所有节点的说法。 See updated code

关于c++ - 类在同一内存位置创建另一个类的多个对象 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18024311/

相关文章:

c++ - C++ 宏中的函数式编程风格 : Is this documented anywhere?

c++ - Arduino Nano - 为什么我的针脚是这样的?

c++ - 错误 : no matching function for call to ‘BSTreeNode<int, int>::BSTreeNode(int, int, NULL, NULL)’ - what's wrong?

c++ - 从文件中读取 unsigned char 的几种不同方法

c++ - 将 OpenGL 纹理打印到文件而不显示?

c++ - CUDA - OpenCV - Visual Studio 2010 中的 C++ 链接错误

c++ - 如何在自定义类中使用 Qt 属性?

python - 在 C++ 应用程序中嵌入 python 环境

c++ - 为什么当我将 int 乘以 double 时会得到错误的值?

c++ - 给定整数 : find odd and even numbers