不能在 C++ 中更改另一个对象中的对象属性
can not change an object's property within another object in C++
我用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;
相关文章:
- PyRun_String返回一个NoneType对象
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 如何创建一个共享对象与另一个.所以在Cmake
- 如何正确实例化静态字段 tat 是另一个类对象
- 给定一个指向对象的超类指针,如何获取对象的大小?
- C++,class,一个返回对象的函数
- 返回一个引用C++中另一个类对象的对象的有效方法
- 在C++中,我想通过使用来自变量(例如字符串)的typename信息,从模板中定义一个类对象
- 有没有一种方法可以从函数中返回一个新对象或对现有对象的引用
- 即使我正在.cpp文件中实例化一个伪对象,.cpp文件内模板函数的定义也不起作用
- C++ 在运行时选择一个随机对象
- 哪个 const 与哪个引用将更改参数并创建一个 const 对象?
- Qt:在一个类中有一个QPainter对象的实例
- 如何异步销毁对象并立即分配一个新对象
- 是否可以创建一个指向对象的智能指针并将此智能指针作为参数传递给构造函数?
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?
- 我有一个 Qt 对象的 2d 数组,我已经用值播种了这些对象。如何访问数组中特定对象的值并更改它们?
- 具有另一个类对象的 std::vector 的类
- C ++如何创建一个即使对象被覆盖也会持续存在的指针?
- 我应该如何在这个房间中创建一个新对象 - opengl