试图使C 类易于使用指针

Trying to make a c++ class easier to use with pointers

本文关键字:易于使 指针      更新时间:2023-10-16

我只是为了学习而尝试使用派生的vector3类做一个向量类。第一个矢量类具有双* V;数组和一些[]运算符的指针,以更轻松的数据访问,vector3还具有x,y,z pointers。

课程的重要部分就像:

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 [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);
};