0

わかりました、テンプレート クラスの << 演算子をオーバーロードしようとして少し行き詰まりました。要件は、<< 演算子が、このクラスに対して定義された void 印刷関数を呼び出さなければならないことです。

テンプレートヘッダーの重要な部分は次のとおりです。

template <class T>
class MyTemp {
public:
    MyTemp();           //constructor

    friend std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a);

    void print(std::ostream& os, char ofc = ' ') const;

そして、これが私の印刷機能です。基本的にはベクトルであり、最後の要素を最初に印刷します:

    template <class T>
void Stack<T>::print(std::ostream& os, char ofc = ' ') const
{
    for ( int i = (fixstack.size()-1); i >= 0 ; --i)
    {
        os << fixstack[i] << ofc;
    }
}

operator<< をオーバーロードする方法は次のとおりです。

    template <class T>
std::ostream& operator<< (std::ostream& os, const Stack<T>& a)
{
    // So here I need to call the a.print() function
}

しかし、「未解決の外部シンボル」エラーが表示されます。だから本当に私は2つの問題があると思います。1 つ目は、上記のエラーを修正する方法です。第二に、それが修正されたら、<< オーバーロード内で a.print(os) を呼び出すだけですか? ただし、ostreamを返す必要があることは知っています。どんな助けでも大歓迎です!

4

3 に答える 3

2

最も簡単なことprintは、(あなたの例のように)パブリックのままにすることです。そのため、オペレーターは友達である必要はありません。

template <class T>
class MyTemp {
public:
    void print(std::ostream& os, char ofc = ' ') const;
};

template <class T>
std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a) {
    a.print(os);
    return os;
}

プライベートにする必要がある場合は、正しいテンプレートの特殊化をフレンドとして宣言する必要があります。friend宣言は、テンプレートではなく、周囲の名前空間で非テンプレート演算子を宣言します。残念ながら、テンプレートをフレンドにするには、事前に宣言する必要があります:

// Declare the templates first
template <class T> class MyTemp;
template <class T> std::ostream& operator<< (std::ostream&, const MyTemp<T>&);

template <class T>
class MyTemp {
public:
    friend std::ostream& operator<< <>(std::ostream& os, const MyTemp<T>& a);
    // With a template thingy here  ^^

private:
    void print(std::ostream& os, char ofc = ' ') const;
};

template <class T>
std::ostream& operator<< (std::ostream& os, const MyTemp<T>& a) {
    a.print(os);
    return os;
}

または、演算子をインラインで定義できます。

template <class T>
class MyTemp {
public:
    friend std::ostream& operator<<(std::ostream& os, const MyTemp<T>& a) {
        a.print(os);
        return os;
    }

private:
    void print(std::ostream& os, char ofc = ' ') const;
};

最後の質問:

第二に、それが修正されたら、オーバーロードa.print(os)内で呼び出すだけ<<ですか? 私はそれが返す必要があることを知っていますostream

実際にはostream- を返す必要があるので、サンプル コードのように、渡されたものを返すだけです。

于 2012-02-23T07:34:54.550 に答える
1

このエラーは、リンカーが認識できなかったシンボルがあることを意味します。このエラーが発生している変数は何ですか。std::stack クラスが利用可能であるため、スタックも確認してください。

于 2012-02-23T07:32:44.860 に答える
0

printメンバー関数は public であるため、 as として宣言する必要はありませoperator<<friend

クラスを使用していることに注意してStackくださいオーバーロード、およびMyTemp上記...

于 2012-02-23T07:30:25.497 に答える