我正在尝试,仅仅为了学习,使用派生的Vector3类创建一个Vector类。第一个Vector类,有一个double * v;数组的指针和一些[]运算符,以便于数据访问,Vector3也有x,y,z指针。
课程的重要部分如下:
class Vector{
protected:
double* v;
int size_;
public:
[ ... a lot of stuff ... ]
double & operator [](int i);
}
class Vector3 : public Vector{
public:
double* x; //Access to v[0]
double* y; //Access to v[1]
double* z; //Access to v[2]
Vector3();
Vector3(double,double,double);
};
所以我的目的是制作像这样的代码:
//You can create a Vector3 and access with x, y, z values:
Vector3 v3 = Vector3(10,9,8);
cout << "Testing v3.x -- v3.y -- v3.z" << endl;
cout << v3.x << " -- " << v3.y << " -- " << v3.z << endl;
//And also change its values
v3.x = 5;
v3.y = 1;
v3.z = 6;
//Now, the two following couts should print the same:
cout << "Testing v3.x -- v3.y -- v3.z and v3[0] -- v3[1] -- v3[2]" << endl;
cout << v3.x << " -- " << v3.y << " -- " << v3.z << endl;
cout << v3[0]<< " -- " << v3[1]<< " -- " << v3[2]<< endl;
我的问题是:
是否可以执行此操作而不修改最后一个代码?
我知道我可以轻松地将这项工作改为v3.x for v3.x [0]或类似的东西,但我希望它更直观。
答案 0 :(得分:0)
如果operator=
类不需要Vector3
,则可以更改引用的指针。
class Vector3 : public Vector{
public:
double& x; //Access to v[0]
double& y; //Access to v[1]
double& z; //Access to v[2]
Vector3();
Vector3(double,double,double);
};