首页 > 解决方案 > 在 C++ 中通过引用传递结构不会更新值

问题描述

我通过引用类 treestr 的一个函数来传递一个结构并将其存储在一个向量中。

然后通过引用另一个函数传递相同的结构并对结构的数据成员执行一些计算。该数据成员在原始结构中得到更新,但在向量中存储的结构中没有得到更新。

(抱歉有任何错误,C++ 新手,堆栈溢出新手)。请帮忙。

//Structure description
Struct point{
int x;
int y;
int cal{0};

};

Struct node{

    point p;
    int data; //value to be updated by func

};

int main(){

    treestr * tree= new treestr(); //create object
    int i=0,n=100;
    vector<node> nob;
    while(i<=n){
        p={1,5}; //some values input by user
        node n={p,i};
        nob.push_back(n)//storing the struct node objects seperately in a 
                         //vector
        treestr->insert(n);  //inserting into tree class
        i++;
        }
    //calling func to do some computation on the struct objects inserted
    for(i=0;i<n;i++){
        int x=tree->func(nob[i]);
        cout<<x.cal; //getting updated values from the function
        }

    for(i=0;i<N;i++){
        tree->func2(nob[i]);
    }
    return 0;
}

//class description
class treestr{
    vector<node> buck; 
    insert(node& n){
        buck.push_back(n);
        //store nodes
    }

    func(node& n){
        //calculations
        return n.cal; Value got updated in main.
    }
    func2(node &n){
        int val1=n.cal; //this assigns updated value
        int val2=buck[i].p.cal; //this assigns 0(default value)
        if(val1==val2){ //never matches, val2 is 0 for all objects, val1 is 
                           //not after getting updated
        //do something
         }
    }

};

cal 在 main 函数中更新,但在我存储的类中没有更新。请忽略语法和句法错误,代码返回正确的输出但是这是我需要改进我的代码的东西。

有什么可能的原因吗??

标签: c++c++11struct

解决方案


尝试改变 node n={1,5,0}

node * n;
node -> x = 1;
node -> y = 5;
node -> cal = 0;

根据我对指针的了解,您需要单独分配每个值。还

tree->insert(n)

需要是

tree.insert(n)

另一件事

int node.cal=tree->func(n);

不知道这应该做什么,但我知道它不会工作。'int' 必须在变量名之前。当calnode您的呼叫访问时需要是一个->并且当functree它访问时需要是一个.


推荐阅读