尝试重载模板类朋友的错误<<操作者

时间:2018-04-08 00:29:16

标签: c++ templates overloading friend-function template-classes

尝试编写更好的数组类型版本我遇到了一个问题。由于某种原因,声明无效。它抛出了一堆奇怪的错误。试图查找问题,但到目前为止还没有找到任何东西。这是代码:

Template <class T>
class SafeArray {

private:
    int size;
    int elements;
    int index;
    T* arr;

public:

    SafeArray(int n);
    ~SafeArray();
    void push_back(T item);
    void resize(int size);
    friend std::ostream& operator << (std::ostream& os, const SafeArray<T>& ar)


};

在课堂外实施:

template<class T>
std::ostream& operator << <T> (std::ostream& os, const SafeArray<T> & arr) {

    for (int i = 0; i < arr.elements; i++) {
        std::cout << arr[i] << " ";
    }

    std::cout << std::endl;

    return os;
}

1 个答案:

答案 0 :(得分:0)

如果您需要friend templatefriend声明应为

template <class T>
class SafeArray {
    ...
    template<class X>
    friend std::ostream& operator << (std::ostream& os, const SafeArray<X>& ar);
};

实施应该是

template<class T>
std::ostream& operator << (std::ostream& os, const SafeArray<T> & arr) {
    ...
}

LIVE

顺便说一句:在operator<<的实施中,我认为std::cout << arr[i] << " ";应为std::cout << arr.arr[i] << " ";