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"
4

1 に答える 1

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ため、明示的に を使用したことに注意してください。ostreamstd

于 2012-04-28T18:05:59.003 に答える