2012-04-28 108 views
1

我必須重載插入運算符才能以矩陣格式查看我的類對象。我寫了代碼,但有些地方是錯的。當我將它包含到我的代碼中並嘗試構建時,編譯器會給我提供大量的錯誤;當我評論這一部分時,錯誤消失了,程序正常工作。下面是代碼:插入運算符重載有什麼問題? (<<運算符)

template <class itemType> 
ostream & operator<< (ostream & os, const Storage2D<itemType> & rhs) 
{ 
    node<itemType>* ptrRow = rhs.head; 
    node<itemType>* ptrColumn = rhs.head; 
    for(; ptrColumn->down != NULL; ptrColumn = ptrColumn->down) 
    { 
     ptrRow = ptrColumn; 
     for(; ptrRow->right != NULL; ptrRow = ptrRow->right) 
     { 
      os << ptrRow->info << setw(10); 
     } 
     os << ptrRow->info << setw(10) << endl; 
    } 

    return os; 
} 

這裏是我試圖用從主函數重載:

Storage2D<double> m(row, column); 
cout << m; 

這不是階級Storage2D的成員函數,它是類的範圍之外書面Storage2D在實現文件中。

這將是偉大的,如果你幫助我,在此先感謝。

編輯:這是我的代碼的其餘部分。該Storage2D.h文件:

template <class itemType> 
struct node 
{ 
    itemType info; 
    node* right; 
    node* down; 

    node() 
    {} 

    node(itemType data, node* r = NULL, node* d = NULL) 
    { 
     info = data; 
     right = r; 
     down = d; 
    } 
}; 

template <class itemType> 
class Storage2D 
{ 
public: 
    Storage2D(const int & , const int &);  //constructor 
    //~Storage2D();        //destructor 
    //Storage2D(const Storage2D &);    //deep copy constructor 

private: 
    node<itemType>* head; 
}; 

ostream& operator<< (ostream & os, const Storage2D & rhs); 

#include "Storage2D.cpp" 
+3

我們需要看到錯誤消息。理想情況下,您還可以向我們展示一個小型(<100行)自包含測試案例,以證明問題;你所顯示的代碼不足以知道什麼是錯的。 – zwol 2012-04-28 17:57:20

+2

通常,當你問如何解決「如果我做X我得到錯誤」性質的問題時,你應該在問題中包含至少第一個錯誤的副本。 – 2012-04-28 17:59:12

+0

在猜測你需要讓操作員成爲朋友,但我們需要確認錯誤。 – 111111 2012-04-28 17:59:50

回答

2

head是私有的,因此運營商需要一個朋友,所以它可以訪問這些數據成員。它也需要被聲明爲自Storage2D函數模板是一個類模板:

#include <iostream> // for std::ostream 

template <class itemType> 
class storage2D { 
// as before 
template <typename T> 
friend std::ostream& operator<< (std::ostream & os, const Storage2D<T> & rhs); 
}; 

// declaration 
template <typename T> 
std::ostream& operator<< (std::ostream & os, const Storage2D<T> & rhs); 

請注意,我已經明確使用std::ostream,因爲ostream是在std命名空間。

+0

此修復程序幫助了很多錯誤,但仍然存在4個錯誤。我想它不認可ostream&作爲返回類型。我應該加入一些圖書館來使用它嗎?

 syntax error : missing ';' before '&' \t syntax error : missing ';' before '' \t missing type specifier - int assumed. Note: C++ does not support default-int missing type specifier - int assumed. Note: C++ does not support default-int All for this line: ostream& operator<< (ostream & os, const Storage2D & rhs);
2012-04-28 18:21:30

+0

@MertToka這可能是因爲你沒有包含,你可能需要使用'std'命名空間。我編輯了我的答案。 – juanchopanza 2012-04-28 18:25:12

+0

非常感謝,它終於有效。順便說一句,我很抱歉我的命令編輯不好。我對HTML代碼完全陌生。 – 2012-04-28 18:28:38