2015-08-31 89 views
-1

這裏是我的任務:陣列模板對象

實現模板類這將表示長方體,其中長度,寬度和高度可以是任何數據類型。 長方體的數組也可以是模板函數的參數,所以需要重載所有需要的運算符。 (當比較長方體,更大的是一個體積較大)

這裏是我做過什麼:

#include <iostream> 

using namespace std; 

template <class T> 
class cuboid{ 
private: 
    int length_of_array; 
    T length, width, height; 
    T * arr; 
public: 
    cuboid(); 
    cuboid(T *, int); 
    cuboid(T, T, T); 
    ~cuboid(); 
    cuboid(const cuboid &); 
    T volume(); 
}; 

template <class T> 
cuboid<T>::cuboid(){ 
} 

template <class T> 
cuboid<T>::cuboid (T *n, int len){ 
    length_of_array = len; 
    arr = new cuboid <T> [length_of_array]; 
    for(int i = 0; i < length_of_array; i++){ 
    arr[i] = n[i]; 
    } 
} 

template <class T> 
cuboid<T>::cuboid(T o, T s, T v){ 
    length = o; 
    width = s; 
    height = v; 
} 

template <class T> 
cuboid<T>::~cuboid(){ 
    delete [] arr; 
    arr = 0; 
} 

template <class T> 
T cuboid<T>::volume(){ 
    return length * width * height; 
} 

template <class T> 
cuboid<T>::cuboid(const cuboid & source){ 
    length_of_array = source.length_of_array; 
    arr = new cuboid <T> [length_of_array]; 
    for(int i = 0; i < length_of_array; i++){ 
    arr[i] = source.arr[i]; 
    } 
} 

int main(){ 
    int a, b, c, length; 
    cuboid <int> *n; 
    cout << "How many cuboids array contains? " << endl; 
    cin >> length; 
    n = new cuboid <int> [length]; 
    for(int i = 0; i < length; i++){ 
    cin >> a >> b >> c; 
    n[i] = cuboid <int> (a,b,c); 
    } 
    cuboid <int> arr(n, length); 
} 

我不能編譯(因爲在主程序最後一行)。任何想法?

+0

一個非常明顯違反你應該表現出確切的錯誤信息以及代碼 –

+0

最後一行需要一個構造函數,其中包含'cuboid *'和'int'。你沒有任何這樣的構造函數。 –

回答

2

如果你看看你的編譯錯誤:

main.cpp:70:31: error: no matching function for call to 'cuboid<int>::cuboid(cuboid<int>*&, int&)' 
    cuboid <int> arr(n, length); 
          ^

它會告訴你,你沒有適當的構造。您正嘗試撥打cuboid<int>(cuboid<int>*, int),但您擁有的是cuboid<int>(int*, int)。現在,我可以告訴你如何解決這個問題,但我會解決你的其他問題:你的設計。

你的問題是:您的解決方案到的

Realize template class which will represent cuboid, where length, width and height can be any data type.

及部分非常有意義:

template <class T> 
class cuboid { 
private: 
    T length, width, height; 
}; 

但是爲什麼它T*和長度?數組是什麼?爲什麼你將該數組賦值給構造函數中的cuboid*?該代碼只會編譯,因爲您從未實例化該構造函數。如果你想要一個cuboid的集合,正確的方法是使用一個容器類。喜歡的東西:

std::vector<cuboid<int>> cuboids; 
for (int i = 0; i < length; ++i) { 
    cin >> a >> b >> c; 
    cuboids.push_back(cuboid(a, b, c)); 
} 

寫一個類,它是一個cuboid他們的集合,即使你正確地寫,是的single responsibility principle

0

對於cuboid<int>你必須接受int*, int參數,而不是cuboid<int>*, int構造。你應該寫一個拷貝構造函數:

cuboid(const cuboid<T>&); 

或(在這種情況下更簡單明瞭)從另一個cuboid指針構造:

cuboid(const cuboid<T>*) 

或(不鼓勵)提供一個getter訪問內部數組:

const T* get_arr() const; 

(和改變cuboid<T>::cuboid(T*, int)構造採取const T*)。

+0

嗯,我認爲他需要一個來自cuboid *的構造函數,在這種情況下,不是複製構造函數。 – BlackCat

+0

@BlackCat複製構造函數在這種情況下是最習慣的(仍然可以在解引用後使用指針)。然而,我在回答中提到的第二個選項就是你所說的(期望它具有'const')。 – BartoszKP

+0

非常感謝! ! ! – Igor