2013-11-15 61 views
0

我試圖創建一個通用的功能,這需要在同一類的兩個對象的通用功能,並返回相同的對象爲兩個不同的類

這是我的兩個類:Point2DPoint3D

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

有人可以請幫我謝謝

+0

搜索模板專業化。 iirc(很長一段時間沒有編寫C++),你可以對某些類型參數有一個明確的專門化。然而,我只是想知道爲什麼你想在這裏使用模板方法?... –

+0

哈哈它的一個功課問題,因此必須這樣做 – Computernerd

回答

2

我想你可以設置一個DIFF功能爲每個類。

類的Point2D與:

Point2d Diff(Point2D &d) { 
    Point2d pt; 
    pt.x = this->x - d.x; 
    pt.y = this->y - d.y; 
    return pt; 
} 

和類三維點:

Point3d Diff(Point3D &d) { 
    Point3d pt; 
    pt.x = this->x - d.x; 
    pt.y = this->y - d.y; 
    pt.z = this->z - d.z; 
    return pt; 
} 

那麼,你的功能是這樣寫:

template T PointDiff(T pt1, T pt2) { 
     return pt1.Diff(pt2); 
} 

我希望這將有助於您。

+0

**爲每個類**設置一個Diff函數,是否意味着我添加了Diff函數的類? – Computernerd

+0

是的,您將Diff函數添加到類Point2D和Point3D。 – yanchong

0

您可以覆蓋減去運營商爲每個類:

Point2D operator-(Point2D &pt1, Point2D &pt2) 
{ 
    Point2D ret; 

    ret.x = pt1.x - pt2.x; 
    ret.y = pt2.y - pt2.y; 

    return ret; 
} 

Point3D operator-(Point3D &pt1, Point3D &pt2) 
{ 
    Point3D ret; 

    ret.x = pt1.x - pt2.x; 
    ret.y = pt2.y - pt2.y; 
    ret.z = pt1.z - pt2.z; 

    return ret; 
} 

您還需要聲明operator-爲兩個類的一個朋友:

class Point2D 
{ 
public: 
    Point2D(); 
    Point2D(int,int); 

    int getX() const; 
    int getY() const; 

    void setX(int); 
    void setY(int); 

    friend Point2D operator-(Point2D &pt1, Point2D &pt2); 
protected: 

    int x; 
    int y; 
}; 

class Point3D:public Point2D 
{ 
public: 
    Point3D(); 
    Point3D(int,int,int); 

    void setZ(int); 

    int getZ() const; 

    friend Point3D operator-(Point3D &pt1, Point3D &pt2); 
protected: 
    int z; 
}; 

然後,您可以在程序中使用此只是通過使用減法

int main(int argc, char **argv) 
{ 
    Point2D a, b, c; 

    a.setX(4); 
    a.setY(5); 
    b.setX(2); 
    b.setY(-10); 

    c = a - b; 

    std::cout << c.getX() << " " << c.getY() << std::endl; 
} 
相關問題