如何修改作为另一个对象属性的列表?

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

这是我的情况。我有一个名为 Node 的类。这个类的属性是一个名为“entry_pipe”的列表和一个用于将元素添加到该列表的方法。这是 Node 类的标题。

class Node {

public:
    std::list<int> entry_pipe = {1};
    double concentration;

    void insert_entry_pipe(int pipe_id);
};

这是网络的 cpp 文件。

void Node::insert_entry_pipe(int pipe_id) {
    entry_pipe.push_back(pipe_id);
}

我还有一个名为网络的课程。此类的属性是称为“节点”的先例对象的列表。此外,它还有一个方法可以返回“节点”列表中给定索引的节点。这是网络类的标题。

class Network {

public:
    list<Node> Nodes;
    Node* Nget(int);
};

这是网络的 cpp 文件。

Node* Network::Nget(int index){
    auto it = Nodes.begin();
    for(int i=0; i<index; i++){
        ++it;
    }
    return &(*it);
}

我的问题...

我无法从网络方法修改节点的“entry_pipe”属性。换句话说,我在网络中有一个第二个方法,我试图修改特定节点的“entry_pipe”属性。此节点对象存储在网络对象的“节点”属性中。我正在使用 Nget 方法检索这个对象。

在第二种方法中,我执行这些行:

void Network::second_method(){
   Nget(10)->insert_entry_pipe(1);
   // or
   Nget(10)->entry_pipe.push_back(1);

   //changing the second attributes (it works)
   Nget(10)->concentration = 0.5;
}

不幸的是,上面两行并没有修改Node对象的“entry_pipe”属性。我通过更改第二个属性来确保我拥有正确的对象。这第二个属性称为“浓度”,它有效......使用 CLion 调试工具,我能够看到“浓度”属性已更改但列表没有更改。此外,我用虚拟列表“{1}”初始化“entry_pipe”属性。我无法使用 CLion 调试工具查看该列表,也无法从“second_method”打印该列表。为什么我可以修改“double”属性,但不能修改“list”属性?我是否修改了错误的对象(错误的地址)?

感谢您的帮助!

c++ list class attributes push-back
© www.soinside.com 2019 - 2024. All rights reserved.