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

can not change an object's property within another object in C++

本文关键字:一个对象 对象 属性 C++ 不能      更新时间:2023-10-16

我用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");

看来你有几个问题,前几个:

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

viewName没有初始化,dss是在函数中声明的(这是没有意义的,因为它将在函数返回时被废弃)。

p。您可以像这样更改第二行:

cout << o1.getName() << " " << o1.getDist().getMinI() << endl;

cout << o2.getName() << " " << o2.getDist().getMinI() << endl;

相关文章: