【问题标题】:can not change an object's property within another object in C++不能在 C++ 中更改另一个对象中的对象的属性
【发布时间】:2011-07-17 14:33:13
【问题描述】:

我有以下用 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

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

【问题讨论】:

  • 我很好奇,vector&lt;double&gt; dss = vector&lt;double&gt;(); 行在构造函数中的作用是什么?
  • 当您调用o1.getDist() 时,您没有返回参考,而是返回了整个班级。所以v3 保存更改后的值,但o1 没有
  • 说实话,这听起来像是一场噩梦,你到底想达到什么目的?这只是提供访问内部变量的方法的问题。

标签: c++ class pointers object reference


【解决方案1】:

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

cViews* getDist(){ return &dist; }

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

【讨论】:

    【解决方案2】:

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

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

    viewName没有初始化,dss是在函数中声明的(没有意义,函数一返回就报废了)。

    ps。您想像这样更改第二行:

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

    到

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

    你真的应该校对你的代码......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多