C++ 无法更改对象';在C++;
我用C++编写了以下代码:C++ 无法更改对象';在C++;,c++,class,pointers,object,reference,C++,Class,Pointers,Object,Reference,我用C++编写了以下代码: #include<iostream> #include<vector> using namespace std; class cViews { string viewName; double minD; vector<double> dss; public: string minInput1, minInput2; cViews(string); cViews(); vo
#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 Changed
非常感谢您的帮助。谢谢。要更改对象而不是副本,必须使用指针或引用。否则,您只需复制从
getDist()
返回的对象,因此无法更改原始对象
cViews* getDist(){ return &dist; }
...
changeViewN(o1.getDist(), "Changed");
要更改对象而不是副本,必须使用指针或引用。否则,您只需复制从
getDist()
返回的对象,因此无法更改原始对象
cViews* getDist(){ return &dist; }
...
changeViewN(o1.getDist(), "Changed");
看起来你有几个问题,前几个:
cViews::cViews(string str) {
vector<double> dss = vector<double>();
}
cViews::cViews(字符串str){
向量dss=向量();
}
viewName未初始化,dss在函数中声明(这没有意义,因为函数返回后它将被废弃)
另外,您希望更改第二行,如下所示:
cout << o1.getName() << " " << o1.getDist().getMinI() << endl;
cout您似乎遇到了几个问题,前几个:
cViews::cViews(string str) {
vector<double> dss = vector<double>();
}
cViews::cViews(字符串str){
向量dss=向量();
}
viewName未初始化,dss在函数中声明(这没有意义,因为函数返回后它将被废弃)
另外,您希望更改第二行,如下所示:
cout << o1.getName() << " " << o1.getDist().getMinI() << endl;
我很好奇,这行的目的是什么代码>在构造函数中服务?当您调用o1.getDist()
时,您没有返回引用,而是返回整个类。因此,v3
保留更改后的值,但是o1
不老实说,这听起来像是一场噩梦,你到底想实现什么?这只是提供访问内部变量的方法的问题代码>在构造函数中服务?当您调用o1.getDist()
时,您没有返回引用,而是返回整个类。因此,v3
保留更改后的值,但是o1
不老实说,这听起来像是一场噩梦,你到底想实现什么?这只是提供访问内部变量的方法的问题。