c++ - 如何为嵌套在一个模板类里面的类添加友元?比如==函数。
PHP中文网
PHP中文网 2017-04-17 14:47:42
0
2
699
template <typename> class Vector;
template <typename T>
bool operator==(const typename Vector<T>::const_iterator&, const typename Vector<T>::const_iterator&); // 友元声明,签名是这么写吗?

template <typename T>
class Vector {
public:
    class const_iterator: {
        friend bool operator==(const const_iterator& lsh, const const_iteraotr& rhs);
    public:
    };
};


template <typename T>
bool operator==(const typename Vector<T>::const_iterator& lhs, const typename Vector<T>::const_iterator& rhs) { // 友元定义

}

如果直接将==友元在const_iterator里面定义,比较简单,直接写就行。但是我想在类外定义时,就不知道怎么写它的函数签名了。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(2)
小葫芦

最好是這樣寫,你上面寫的那種似乎很難實現
參考

template <typename> struct Vector;

template <typename T>
struct Vector_const_iterator;

template <typename T>
bool operator==(const Vector_const_iterator<T>& lsh, const Vector_const_iterator<T>& rhs);

template <typename T>
struct Vector {
    typedef Vector_const_iterator<T> const_iterator;
};

template <typename T>
struct Vector_const_iterator {
    friend bool operator == <> (const Vector_const_iterator<T>& lsh, const Vector_const_iterator<T>& rhs);
};


template <typename T>
bool operator==(const Vector_const_iterator<T>& lsh, const Vector_const_iterator<T>& rhs) { 
    return true;
}
洪涛

你的函數宣告寫的有點問題,友元只是有存取權限,而不是類別的成員。

template <typename T>
class Vector {
public:
    class const_iterator{
        friend bool operator==(const typename Vector<T>::const_iterator& lsh, 
                               const typename Vector<T>::const_iterator& rhs);
    public:
    };
};


template <typename T>
bool operator==(const typename Vector<T>::const_iterator& lhs, const typename Vector<T>::const_iterator& rhs) { // 友元定义
  return false;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!