亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為模板類重載好友運算符<<

為模板類重載好友運算符<<

C++
一只名叫tom的貓 2019-11-19 14:26:46
我正在嘗試將運算符<<作為模板類Pair的朋友重載,但我不斷收到編譯器警告說friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function對于此代碼:friend ostream& operator<<(ostream&, Pair<T,U>&);它給出第二條警告作為建議說if this is not what you intended, make sure the function template has already been declared and add <> after the function name here這是功能定義template <class T, class U>ostream& operator<<(ostream& out, Pair<T,U>& v){    out << v.val1 << " " << v.val2;}這是全班。template <class T, class U>class Pair{public:    Pair(T v1, U v2) : val1(v1), val2(v2){}    ~Pair(){}    Pair& operator=(const Pair&);    friend ostream& operator<<(ostream&, Pair<T,U>&);private:    T val1;    U val2;};我不確定從推薦警告中可以得出什么,除了我可能必須在朋友聲明中放置某處之外。有誰知道正確的語法嗎?謝謝。
查看完整描述

3 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

您希望使該模板的一個實例(一般稱為“專業化”)成為朋友。您可以通過以下方式進行


template <class T, class U>

class Pair{

public:

    Pair(T v1, U v2) : val1(v1), val2(v2){}

    ~Pair(){}

    Pair& operator=(const Pair&);

    friend ostream& operator<< <> (ostream&, Pair<T,U>&);


private:

    T val1;

    U val2;

};

因為編譯器從參數列表中知道模板參數是T和U,所以您不必將<...>它們放在之間,因此可以將其保留為空。請注意,您必須operator<<在Pair模板上方放置一個聲明,如下所示:


template <class T, class U> class Pair;


template <class T, class U>

ostream& operator<<(ostream& out, Pair<T,U>& v);


// now the Pair template definition...


查看完整回答
反對 回復 2019-11-19
?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

簡單的內聯版本:


template<typename T> class HasFriend {

    private:

        T item;

    public:

       ~HasFriend() {}

       HasFriend(const T &i) : item(i) {}

    friend ostream& operator<<(ostream& os, const HasFriend<T>& x) {

        return os << "s(" << sizeof(x) << ").op<<" << x.item << endl;

    }

};

修改后的模板版本:


template<template<typename /**/> class U, typename V>

ostream& operator<<(ostream &os, const U<V> &x) {

    return os << "s(" << sizeof(x) << ").op<<" << x.item << endl;

}


template<typename T> class HasFriend {

    private:

        T item;

    public:

       ~HasFriend() {}

       HasFriend(const T &i) : item(i) {}

    friend ostream& operator<<<>(ostream&, const HasFriend<T>&);

};


查看完整回答
反對 回復 2019-11-19
  • 3 回答
  • 0 關注
  • 530 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號