c++ - 如何为嵌套在一个模板类里面的类添加友元?比如==函数。
PHP中文网
PHP中文网 2017-04-17 14:47:42
0
2
701
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;
}
いいねを押す +0
洪涛

你的函数声明写的有点问题,友元只是具有访问权限,而不是类的成员。

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;
}
いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!