在C ++中通过引用传递结构不会更新该值

时间:2019-03-30 02:00:16

标签: c++ c++11 struct

我通过引用一个类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在主函数中更新,但在我存储的类中未更新。请忽略语法和语法错误,代码将返回正确的输出,但这是我需要改进代码的地方。

任何可能的原因?

1 个答案:

答案 0 :(得分:-1)

尝试更改 return $this->embedsMany('App\Website', 'website_ids', '_id');

node n={1,5,0}

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

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

需要成为

tree->insert(n)

另一件事

tree.insert(n)

不知道这应该做什么,但是我知道它不会起作用。 'int'必须在变量名之前。从int node.cal=tree->func(n);访问cal时,您的呼叫必须是node,而从->访问func时,呼叫必须是tree