gpt4 book ai didi

c++ - 不能在 C++ 中的另一个对象中更改对象的属性

转载 作者:行者123 更新时间:2023-11-28 01:04:58 25 4
gpt4 key购买 nike

我有以下用 C++ 编写的代码:

#include<iostream>
#include<vector>

using namespace std;

class cViews {
string viewName;
double minD;
vector<double> dss;

public:
string minInput1, minInput2;
cViews(string);
cViews();
void setName(string s) { viewName = s; }
string getName() { return viewName; }
void setMinI(string m) { minInput1 = m; }
string getMinI() { return minInput1; }
void setMinD(double d) { minD = d; }
double getMinD() { return minD; }
void addD(vector<double> k){ dss = k; }
vector<double> getD(){ return dss; }
};

cViews::cViews(string str) {
viewName = str;
vector<double> dss = vector<double>();
}

cViews::cViews() {
vector<double> dss = vector<double>();
}

class Obj{
string name;
cViews dist;
public:
Obj(string);
void setName(string s) { name = s; }
string getName() { return name; }
void addDist(cViews k){ dist = k; }
cViews getDist(){ return dist; }
};

Obj::Obj(string str) {
name = str;
cViews dist();
}

void changeViewN(cViews *v, string s){
v->setMinI(s);
}

int main(){
Obj o1("Object1");
cViews v3;
cViews v1("View 1");
v1.setMinI("View 2");
v1.setMinD(1);
o1.addDist(v1);
cout << o1.getName() << " " << o1.getDist().getMinI() << endl;
v3 = o1.getDist();
changeViewN(&v3, "Changed");
cout << o1.getName() << " " << o1.getDist().getMinI() << endl;
return 0;
}

输出是:

Object1 View 2
Object1 View 2

这里的问题是我试图更改在另一个对象中创建的对象的值。

输出应该是:

Object1 View 2
Object1 Changed

非常感谢任何帮助。谢谢。

最佳答案

要更改对象而不是拷贝,您必须使用指针或引用。否则您只是复制从 getDist() 返回的对象,因此无法更改原始对象。

cViews* getDist(){ return &dist; }

...
changeViewN(o1.getDist(), "Changed");

关于c++ - 不能在 C++ 中的另一个对象中更改对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6724497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com