2012-02-21 33 views
0

我做了我自己的類模板來維護任何類型對象的元素對。現在我打算將這個模板用於另一個自己的類MyPoint。這包含一個點的3D座標。我想我需要進一步修改,因爲我的最終目標是使用此PairInfor<MyPoint>作爲vector<PairInfor<MyPoint> >並再次使用vector<vector<PairInfor<MyPoint> > >。所以,我需要你的支持來修改這個,因爲我沒有足夠的知識來準備這種類型的模板。使用自己的類模板維護一對elemts

我從其他一些班級和書籍中獲得助理,但我需要將最常見的功能包括在內。任何人都可以幫忙嗎?

這是我的模板類;

// class to accomadate two values 
//------------------------------- 

#include <stdlib.h> 
#include <iostream>  

template <class Type> 
class PairInfor { 

private: 
     /// two elements of the pair 
    Type x[2]; 


public: 
    // Default constructor. 
    PairInfor() { x[0] = x[1] = -1; } 

    // other Constructors. 
    PairInfor(Type xv, Type yv) { 
     x[0] = xv; x[1] = yv; 
    } 

    PairInfor(const Type *v) { x[0] = v[0]; x[1] = v[1]; } 


    //constructor for Coping 
    PairInfor(const PairInfor &v) { x[0] = v.x[0]; x[1] = v.x[1]; } 

    // Destructor. 
    ~PairInfor() {} 

     // assignament 
     PairInfor& operator=(const PairInfor &v) 
      { x[0] = v.x[0]; x[1] = v.x[1]; 
      return *this; 
      } 


    // Element access, for getting. 
    Type V1() const { return x[0]; } 


    // Element access, for getting. 
    Type V2() const { return x[1]; } 


    // Element access, for getting. 
    Type operator[] (int i) const { return x[i]; } 



    // Element access, for writing. 
    Type &V1() { return x[0]; } 


    // Element access, for writing. 
    Type &V2() { return x[1]; } 


    // Element access, for writing. 
    Type &operator[] (int i) { return x[i]; } 


    // Return a constant reference to the pair 
    const class PairInfor &infor() const { return *this; } 

    // Return a reference to the pair 
    PairInfor &infor() { return *this; } 

    // comparing two pair packets 
    friend bool operator == (const PairInfor &v1, const PairInfor &v2) 
    { 
     return v1.x[0] == v2.x[0] && v1.x[1] == v2.x[1]; 
    } 

}; 

當我使用這個模板類,我也得到以下錯誤。

\include\PairInfor.hpp In constructor `PairInfor<Type>::PairInfor() [with Type = MyPoint]': 
\myprogf.cpp instantiated from here 
\include\PairInfor.hpp invalid conversion from `int' to `char*' 
\include\PairInfor.hpp initializing argument 1 of `MyPoint::MyPoint(char*)' 
\Makefile.win [Build Error] [myprogf.o] Error 1 

我該如何解決這個錯誤。 PairInfor中的默認構造函數有錯誤。我該如何解決這個問題? 在此先感謝。

+0

...你的具體問題是? – 2012-02-21 13:10:37

+0

@Georg Fritzsche:希望添加缺少的常用函數以便能夠用作通用向量<>類。例如clear()等等。 – gnp 2012-02-21 13:19:48

+0

你試過了嗎?什麼不行? – 2012-02-21 13:21:56

回答

0

以下行不會對任何類型的工作:

PairInfor() { x[0] = x[1] = -1; } 

您試圖指派一個整數,但Type可能不支持。 MyPoint不會,所以錯誤。
您應該默認初始化的成員:

PairInfor() : x() {} 

注意std::pair可能包括你的需求了。

+0

好吧。謝謝。我可以製作不同的構造函數嗎?整數和雙倍所有其他類型的示例。如果可以的話,我認爲它效率更高。那麼,相關的構造函數是否會被編譯器自動採用?請對此進行任何修改。謝謝。 – gnp 2012-02-21 15:04:20

+0

@user:是的,您可以提供多個構造函數 - 您已經爲'PairInfor'(默認&複製ctor和'Type *')做了這樣的構造函數。編譯器將選擇最佳匹配。 – 2012-02-21 15:13:51

相關問題