无法更改向量中的 class 个对象
Cannot change class objects within vector
我很难理解如何更改存储在向量中的 class 对象的值。从下面的例子来看,我认为“法拉利”在我改变颜色后会变成黄色,但它仍然是黑色。
据我了解,这与我每次都制作一个新的矢量副本有关,因此不会更改我想要的对象。我读过,将向量写成引用而不是像这样可能会有所帮助:vector<Car> &cars;
,但这会产生错误“引用变量 'cars' 需要初始化程序”,我不知道如何解决.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Car
{
public:
string brand;
string color;
Car(string brand, string color)
: brand(brand), color(color)
{
}
// setter
void setColor(string newColor)
{
color = newColor;
}
};
int main()
{
vector<Car> cars;
cars.push_back(Car("bmw", "blue"));
cars.push_back(Car("tesla", "red"));
cars.push_back(Car("ferrari", "black"));
for (Car car : cars)
{
if (car.brand == "ferrari")
{
car.setColor("yellow");
}
}
for (Car car : cars)
{
cout << car.brand << " " << car.color << endl;
}
return 0;
}
在您的 for
循环中:
for (Car car : cars)
所以当它循环时,它会复制 cars
个元素,而不是元素本身。
将其更改为
for (Car &car : cars)
在for (Car car : cars)
中,car
是对应向量元素的副本。更改副本不会影响原件。
如果要修改元素,请使用for (Car &car : cars)
。即使您只想阅读(打印)它们,也可以使用 for (const Car &car : cars)
来避免您当前正在制作的不必要的副本。
另请注意,您的构造函数和 setter 不是最理想的。他们需要一些 std::move
s:
class Car
{
public:
string brand;
string color;
Car(string brand, string color)
: brand(std::move(brand)), color(std::move(color))
{
}
// setter
void setColor(string newColor)
{
color = std::move(newColor);
}
};
我很难理解如何更改存储在向量中的 class 对象的值。从下面的例子来看,我认为“法拉利”在我改变颜色后会变成黄色,但它仍然是黑色。
据我了解,这与我每次都制作一个新的矢量副本有关,因此不会更改我想要的对象。我读过,将向量写成引用而不是像这样可能会有所帮助:vector<Car> &cars;
,但这会产生错误“引用变量 'cars' 需要初始化程序”,我不知道如何解决.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Car
{
public:
string brand;
string color;
Car(string brand, string color)
: brand(brand), color(color)
{
}
// setter
void setColor(string newColor)
{
color = newColor;
}
};
int main()
{
vector<Car> cars;
cars.push_back(Car("bmw", "blue"));
cars.push_back(Car("tesla", "red"));
cars.push_back(Car("ferrari", "black"));
for (Car car : cars)
{
if (car.brand == "ferrari")
{
car.setColor("yellow");
}
}
for (Car car : cars)
{
cout << car.brand << " " << car.color << endl;
}
return 0;
}
在您的 for
循环中:
for (Car car : cars)
所以当它循环时,它会复制 cars
个元素,而不是元素本身。
将其更改为
for (Car &car : cars)
在for (Car car : cars)
中,car
是对应向量元素的副本。更改副本不会影响原件。
如果要修改元素,请使用for (Car &car : cars)
。即使您只想阅读(打印)它们,也可以使用 for (const Car &car : cars)
来避免您当前正在制作的不必要的副本。
另请注意,您的构造函数和 setter 不是最理想的。他们需要一些 std::move
s:
class Car
{
public:
string brand;
string color;
Car(string brand, string color)
: brand(std::move(brand)), color(std::move(color))
{
}
// setter
void setColor(string newColor)
{
color = std::move(newColor);
}
};