2014-01-16 38 views
8

我試圖創建一個名爲tableaux的對象,它基本上是一些無符號整型的向量(它們就像矩陣,除了行可以有不同的長度),我寫了一些算法。主要問題是我想從vector類繼承這些對象的迭代器,我不知道如何。如何從STL類「繼承」一個迭代器?

我讀過幾個相關的問題和答案,這是很容易的,我只是繼承std::vector<std::vector<unsigned int> >公開,但共識是,這是壞的沒有虛析構函數或任何STL容器的原因。所以我決定嘗試並通過構圖「繼承」。下面是我想要達到一定程度,最小的例子:

#include <vector> 
#include <iostream> 

class tableau { 
    private: 
    std::vector<std::vector<unsigned int> > rep; 
    public: 
    using std::vector<std::vector<unsigned int> >::iterator; 
    void push_back(std::vector<unsigned int> const& new_row) { 
     rep.push_back(new_row); 
    } 
}; 

int main() { 
    tableau t1; 
    std::vector<unsigned int> row1(10); 
    std::vector<unsigned int> row2(8); 

    t1.push_back(row1); 
    t1.push_back(row2); 

    tableau::iterator it = t1.begin(); 
    for (; it != t1.end(); ++it) { 
    //display rows of tableau 
    } 
    return 0; 
} 

但隨後G ++給我的錯誤:類型「std::vector<std::vector<unsigned int> >」沒有爲類型「畫面」基本類型。我剛剛開始學習C++,所以如果我做了一些愚蠢的事,請保持溫柔。如果你想要更多我寫的實際代碼,請告訴我。

+3

總的來說,這是一個非常好的測試用例。做得好。 :) –

回答

10

你的第一個問題是,using不允許你從任意無關的類型中竊取類型(儘管你可以使用typedef來實現這一點)。此外,您沒有begin()end()成員。

解決這些問題將導致以下:

#include <vector> 
#include <iostream> 

class tableau { 
    private: 
    std::vector<std::vector<unsigned int> > rep; 
    public: 
    typedef std::vector<std::vector<unsigned int> >::iterator iterator; 
    void push_back(std::vector<unsigned int> const& new_row) { 
     rep.push_back(new_row); 
    } 
    iterator begin() { return rep.begin(); } 
    iterator end() { return rep.end(); } 
}; 

int main() { 
    tableau t1; 
    std::vector<unsigned int> row1(10); 
    std::vector<unsigned int> row2(8); 

    t1.push_back(row1); 
    t1.push_back(row2); 

    tableau::iterator it = t1.begin(); 
    for (; it != t1.end(); ++it) { 
    //display rows of tableau 
    } 
    return 0; 
} 

然而,你的做法意味着你將不得不換你要調用每一個函數。

如果我是你,我會堅持繼承:雖然你引用的建議是正確的,但這並不意味着繼承是不可能的。你永遠不會想要通過指針到基地多態地使用tableau,所以只需簡單地記錄一下,沒有人應該嘗試這樣做,並且你會沒事的。

(當你使用「組合」的這就是所謂的「創作」。你問如何「撰寫」的載體。)

+0

好的,作曲的概念現在更有意義了,謝謝。在這種情況下,我想我會堅持繼承。 –

+0

@Joseph:我認爲這是明智的。 –

+0

+1容器的繼承並不像有些人想要的那樣糟糕。 – jrok