2014-01-30 30 views
-1

我想,只是爲了學習,使派生的Vector3類的Vector類。第一個Vector類,有一個double * v;數組的指針和一些[]運算符更容易訪問數據,Vector3也有x,y,z指針。試圖讓一個C++類更容易使用指針

類的重要的部分是這樣的:

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 v3.x [0]或類似的東西,但我希望它更直觀。

+0

看看GLM庫如何做到這一點。 TL; DR使用工會** **很多兼容性檢查。你的方法需要大量的冗餘。 –

回答

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); 
}; 
+0

謝謝!這正是我正在尋找的。 –