在向量内更改变量的值不会改变其在向量外的值
Changing value of variable inside vector doesn't change its value outside of vector
我在类 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
对象p1
p4
main
函数中要修改,那么它们不会。
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;
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 变量没有改变?通过向量的函数调用
- C++在不同线程中改变向量
- 在向量内更改变量的值不会改变其在向量外的值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 通过引用传递向量的值在传递的原始向量中不会改变
- 分配矩阵列标准偏差的向量正在改变其值(RcppArmadillo)
- 应该很琐碎,为什么我不能改变我的向量的值
- 一个元素不能改变的非守恒向量
- 为什么向量分配会改变分配的向量
- 提升::p tr_向量改变元素顺序
- 为什么std::sort()改变了排序向量
- 一些向量元素不会改变
- c++的共享指针向量.如果在vector外强制转换,它会改变vector中的指针吗?< / h1 >
- 使用swap vs改变指向向量的指针
- 将向量数组作为函数参数传递(值不会改变)
- 为什么我的向量中的字符串没有改变值?
- 在c++中,如何改变元素在一个向量中的位置,并对另一个不同的向量进行相同的改变