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

标签 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();
    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/

相关文章:

c - 为什么我不能像 C 中的指针一样对待数组?

c - 为什么我总是覆盖链接列表中指向的内容?

c++ - static_cast 被滥用了吗?

java - 错误 :Issue with reading text file in class I created

c++ - 如何在不知道旧密码的情况下设置用户帐户密码?

Python:什么时候应该使用子类而不是方法?

python - 在python中初始化类内的子类

c++ - 与基本面斗争。特别是 char[]、char* 和从数组中读取。也许我应该使用字符串类型

c++ - DLL 可以通过调用 EXE 加载资源吗?

c++ - 使用 CUDA 的 Thrust 库进行数组缩减