簡體   English   中英

operator <<重載以調用打印功能故障

[英]operator<< overloading to call a print function trouble

好吧,我有點想為我的模板類重載<<操作符。 要求是<<操作符必須調用為此類定義的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
}

但是我收到“無法解析的外部符號”錯誤。 所以我真的有兩個問題。 第一種是解決以上錯誤的方法。 其次,一旦修復,我將在<<重載內調用a.print(os)嗎? 我知道它需要返回一個ostream。 任何幫助將不勝感激!

最簡單的方法是公開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因此只需返回傳入的那個,就像我的示例代碼中那樣。

此錯誤意味着鏈接器無法識別一個符號。關於什么變量,您將收到此錯誤,並且還請檢查堆棧,因為有一個std :: stack類可用。

由於您的print成員函數是公共的,因此無需將operator<<聲明為friend

請注意,您正在使用Stack類,這是您的重載 ,而上面的MyTemp ...

暫無
暫無

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

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