需要从C 类引用和更新值

Need to reference and update value from nested class C++

本文关键字:更新 引用      更新时间:2023-10-16

与我同在,我是C 的新手。我正在尝试更新存储在向量中的值,但是我遇到了此错误:

 non-const lvalue reference to type 'Node'

我正在使用std::vector周围的简单包装器,因此我可以共享contains和其他等方法(类似于Java中的ArrayList的方式)。

#include <vector>
using namespace std;
template <class T> class NewFrames {
public:
    // truncated ...
    bool contains(T data) {
        for(int i = 0; i < this->vec->size(); i++) {
            if(this->vec->at(i) == data) {
                return true;
            }
        }
        return false;
    }
    int indexOf(T data) {
        for(int i = 0; i < this->vec->size(); i++) {
            if(this->vec->at(i) == data) {
                return i;
            }
        }
        return -1;
    }
    T get(int index) {
        if(index > this->vec->size()) {
            throw std::out_of_range("Cannot get index that exceeds the capacity");
        }
        return this->vec->at(index);
    }
private:
    vector<T> *vec;
};
#endif // A2_NEWFRAMES_H

使用此包装器的类定义如下:

#include "Page.h"
#include "NewFrames.h"
class Algo {
private:
    typedef struct Node {
        unsigned reference:1;
        int data;
        unsigned long _time;
        Node() { }
        Node(int data) {
            this->data = data;
            this->reference = 0;
            this->_time = (unsigned long) time(NULL);
        }
    } Node;
    unsigned _faults;
    Page page;
    NewFrames<Node> *frames;
};

我需要参考向量内部的Node对象之一,但是我需要能够将reference更改为其他值。从我发现的东西来看,我需要这样做:

const Node &n = this->frames->get(this->frames->indexOf(data));

我尝试使用:

Node n = this->frames->get(this->frames->indexOf(data));
n.reference = 1;

然后查看调试器中的数据,但是当我稍后检查时,该值不会更新。考虑一下:

const int data = this->page.pages[i];
const bool contains = this->frames->contains(Node(data));
Node node = this->frames->get(index);
for(unsigned i = 0; i < this->page.pages.size(); i++) {
    if(node == NULL && !contains) {
        // add node
    } else if(contains) {
        Node n = this->frames->get(this->frames->indexOf(data));
        if(n.reference == 0) {
            n.reference = 1;
        } else {
            n.reference = 0;
        }
    } else {
        // do other stuff
    }
}

随后通过循环的通过,具有该特定数据值的节点有所不同。

但是,如果我尝试更改n.reference,我会遇到一个错误,因为const阻止对象更改。有什么方法可以得到这个节点,以便可以更改它?我来自友好的爪哇世界,这样的事情会起作用,但是我想知道/理解为什么在C 中不起作用。

Node n = this->frames->get(this->frames->indexOf(data));
n.reference = 1;

这将Node复制CC_7,并将复制存储为对象n。修改副本不会更改原始节点。

最简单的"修复"是使用参考。这意味着将get的返回类型从T更改为T&,然后将前两行更改为

Node& n = this->frames->get(this->frames->indexOf(data));
n.reference = 1;

应该使代码工作。但是,代码中有太多的间接方式,以至于可能还有其他问题尚未出现。正如@NWP在评论中所说的那样,使用vector<T>而不是vector<T>*可以为您节省许多头痛。

当我提供时尚建议时,请摆脱这些this-> s;他们只是噪音。并简化皮带和悬浮器的有效性检查:当您从0循环到vec.size()时,您无需检查访问该元素时的索引是否还可以;将vec.at(i)更改为vec[i]。在get中,请注意,如果index不超出界限,则vec.at(index)会引发异常,因此您可以跳过初始范围检查或保持检查(修复后,以检查实际范围),然后再次使用vec[index]vec.at(index)