在向量内更改变量的值不会改变其在向量外的值

Changing value of variable inside vector doesn't change its value outside of vector

本文关键字:改变 向量 变量      更新时间:2023-10-16

我在类 Figure3D 中有一个类 Point3D 对象的向量。更改矢量内 Point3D 对象坐标的函数不会更改矢量外部 Point3D 对象的坐标。

使用函数 Figure3D::P os(( 我看到在使用函数 Figure3D::Move(( 后矢量内的坐标发生了变化,但使用 Point3D::full_pos(( 我看到 Point3D 对象仍然具有其初始坐标。

#include <vector>
#include <iostream>
#include <math.h>
#define PI acos(-1)
class Point3D {
public:
Point3D()
{
X = 0;
Y = 0;
Z = 0;
}
Point3D(double a, double b, double c) {
X = a;
Y = b;
Z = c;
};
void full_pos() {
std::cout << "Coordinates of the point are: X = " << X << " Y = " << Y << " Z = " << Z << std::endl;
}
void Move(double dx, double dy, double dz) {
X += dx;
Y += dy;
Z += dz;
}
private:
double X, Y, Z;
};
class Figure3D :public Point3D {
public:
Figure3D() {
f.reserve(10);
}
void AddPoint(Point3D *p) {
f.push_back(*p);
}
void Move(double x, double y, double z) {
for (auto it = f.begin(); it != f.end(); it++) {
it->Move(x, y, z);
}
}
void Pos() {
int i = 0;
for (auto it = f.begin(); it != f.end(); it++) {
cout << "Position of point " << i << "  X: " << it->posX() << " Y: " << it->posY() << " Z: " << it->posZ() << std::endl;
i++;
}
}
private:
std::vector<Point3D> f;
};
int main() {
Point3D p1(1, 2, 3), p2(2, 2, 2), p3(5, 4, 7), p4(4, 9, 0);
Figure3D f1;
f1.AddPoint(&p1);
f1.AddPoint(&p2);
f1.AddPoint(&p3);
f1.AddPoint(&p4);
f1.Pos();
p1.full_pos();
f1.Move(10, 10, 10);
f1.Pos();
p1.full_pos();
} 

假设您期望在修改f1对象中矢量中的元素时,Point3D对象p1p4main函数中要修改,那么它们不会。

reson在你做的AddPoint函数中

f.push_back(*p);

矢量存储不同的对象,而不是指针或引用。这与你对derefernece运算符的使用一起,使你在向量中存储对象的副本。修改副本不会修改原件。

你的AddPoint函数是错误的。您正在将指针作为参数传递,但随后您取消引用指针并将Point3D对象的副本存储到您的std::vector中。因此,它应该是:

void AddPoint(Point3D *p) {
f.push_back(p);
}

而不是

void AddPoint(Point3D *p) {
f.push_back(*p);
}

std::vector<Point3D*> f;

而不是

std::vector<Point3D> f;