【问题标题】:Errors trying to overload template class friend << operator尝试重载模板类朋友 << 运算符时出错
【发布时间】:2018-09-17 16:35:10
【问题描述】:

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

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;
}

【问题讨论】:

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


    【解决方案1】:

    如果你想要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

    BTW:在operator&lt;&lt;的实现中,我认为std::cout &lt;&lt; arr[i] &lt;&lt; " ";应该是std::cout &lt;&lt; arr.arr[i] &lt;&lt; " ";

    【讨论】:

    • 我已经这样做了,但我仍然收到错误:错误 C3646:'T':未知的覆盖说明符注意:请参阅正在编译的类模板实例化 'SafeArray' 的引用错误 C2988:无法识别的模板声明/定义错误 C2059:语法错误:“&”错误 C2334:“{”之前的意外标记;跳过明显的函数体
    • @TomatoLV 还有一些问题,看我发布的现场演示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2021-05-18
    相关资源
    最近更新 更多