我試圖創建一個通用的功能,這需要在同一類的兩個對象的通用功能,並返回相同的對象爲兩個不同的類
這是我的兩個類:Point2D
和Point3D
class Point2D
{
public:
Point2D();
Point2D(int,int);
int getX() const;
int getY() const;
void setX(int);
void setY(int);
protected:
int x;
int y;
};
class Point3D:public Point2D
{
public: Point3D();
Point3D(int,int,int);
void setZ(int);
int getZ() const;
protected:
int z;
};
對於的Point2D:我想返回一個Point2D對象,其X,Y座標是2的Point2D之間的差異對象
對於三維點:我想返回一個三維點對象,其X,Y,Z座標是differenc es之間2個Point3D對象
我可以創建一個通用函數來處理這兩個? 。
下面是我有這麼遠,但它只能處理Point2D對象,我怎麼三維點對象集成到通用功能如下
型板T PointDiff(T PT1,T PT2)
{
T pt3;pt3.x = pt1.x - pt2.x;
pt3.y = pt1.y - pt2.y;
return pt3;
}
我在想這樣的事情,但問題是,的Point2D對象不具有Z座標
型板T PointDiff(T PT1,T PT2) {
T pt3;pt3.x = pt1.x - pt2.x;
pt3.y = pt1.y - pt2.y;
pt3.z = pt1.z - pt2.z
返回PT3; }
有人可以請幫我謝謝
搜索模板專業化。 iirc(很長一段時間沒有編寫C++),你可以對某些類型參數有一個明確的專門化。然而,我只是想知道爲什麼你想在這裏使用模板方法?... –
哈哈它的一個功課問題,因此必須這樣做 – Computernerd