c++ - 在 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 函数中更新,但在我存储的类中没有更新。请忽略语法和句法错误,代码返回正确的输出但是这是我需要改进我的代码的东西。
有什么可能的原因吗??
解决方案
尝试改变
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' 必须在变量名之前。当cal
从node
您的呼叫访问时需要是一个->
并且当func
从tree
它访问时需要是一个.
推荐阅读
- nginx - Nginx 反向代理和 ZAP
- python - 验证指标停滞不前,而培训不断改进
- css - ngClass 一个条件和其他来自变量
- javascript - 后期更新后React Native和Android Studio的问题
- sql - 有什么办法可以优化这个选择
- python - 在 Python 中,在 while 循环内引发异常会导致内存泄漏吗?
- regex - 在替换部分中使用捕获组之前,使用自定义函数处理它们
- jquery - 传递div而不是页面顶部时如何启动jquery计数?
- xml - PowerShell 给出错误“对象引用未设置为实例对象”
- arrays - 我的代码不会打印出数组索引 0 的正确值