簡體   English   中英

模板二進制搜索樹ostream重載問題

[英]Template Binary Search Tree ostream overloading issue

我嘗試搜索,但找不到解決方案,問題的含義是什么。

friend ostream & operator<<(ostream &os, const BST<T> &rhs);
void helperFunc(ostream & os, Node<T> *root) const;

定義為:

template<class T>
ostream & operator<<(ostream & os, const BST<T> &rhs)
{
    rhs.helperFunc(os, rhs._root);
    os << endl;

return os;
}

template<class T>
void BST<T>::helperFunc(ostream & os, Node<T> *root) const
{
    if (root != NULL)
{
    helperFunc(os, root->left);
    os << root->value << " ";
    helperFunc(os, root->right);
    }
}

我主要使用的是:

void main()
{
BST <int> a;
a.insert(5)
cout << a;
}

我收到以下錯誤消息:

Error   LNK2019 unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class BST<int> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$BST@H@@@Z) referenced in function _main...    

如果需要,將提供任何其他信息。

解決方案是:

template <typename U>
friend ostream & operator<<(ostream & os, const BST<U> &obj);

在模板類中重載operator <<和operator >>有點特殊。 只需評論此聲明,它將起作用:

friend ostream & operator<<(ostream &os, const BST<T> &rhs);

這是因為friend函數實際上不是該類的成員函數。 在類外部定義的重載operator <<函數實際上定義了一個新的模板函數,與類中聲明的函數不同。 盡管它們具有相同的“模板類T”,但實際上它們是不同的功能。 因此,編譯錯誤告訴您未定義該類的operator <<函數。

由於我們在類之外重載了新的模板運算符<<,因此我們可以擺脫類中聲明的friend函數。 以下代碼將起作用,並且我更改了一些其他功能以進行詳細說明:

#include <iostream>
using namespace std;

template<class T>
class Node {

};

template<class T>
class BST {
public:
// friend ostream & operator<<(ostream & os, const BST<int> &rhs);
    void helperFunc(ostream & os, Node<T> *root) const;
};

template<class T>
ostream & operator<<(ostream & os, const BST<T> &rhs)
{
    cout << "success" << endl;
    // rhs.helperFunc(os, rhs._root);
    // os << endl;

    return os;
}

template<class T>
void BST<T>::helperFunc(ostream & os, Node<T> *root) const
{
    if (root != NULL)
{
    helperFunc(os, root->left);
    os << root->value << " ";
    helperFunc(os, root->right);
    }
}

int main()
{
    BST<int> a;
    // a.insert(5);
    cout << a;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM