首页 > 解决方案 > 为什么不能在 C++ 中为动态数组重载插入运算符?

问题描述

我是 C++ 新手。只是出于好奇,我想看看当我尝试为一类动态数组重载插入“>>”运算符时会发生什么。我认为我正在尝试做的事情是不可能的。但是谁能解释这个错误是什么意思?(代码下方的错误)

#include<iostream>
using namespace std;

template<class Type>
class Array{
    private:
    int length;
    Type* ptrarr;

    public:
        int size() const;
        Type* get_array() const;
        friend istream& operator >> (istream& s, Array<Type>& arr);

};

template<class Type>
int Array<Type>::size() const{
    return length;
}

template<class Type>
Type* Array<Type>::get_array() const{
    return ptrarr;
}

template<class Type>
istream& operator >> (istream& s, Array<Type>& arr){
    cout << "Enter length of array"; cin >> arr.length;
    arr.ptrarr = new Type[arr.length];
    for(int i = 0; i < arr.length; i++){
        cout << "Array[" << i << "] = ";
        cin >> *(arr.ptrarr + i);
    }
    return s;
}


int main(){
    Array<int> intarray;
    cin >> intarray;
    int* ptr = intarray.get_array();
    for(int i =0; i < intarray.size(); i++)
        cout << *(ptr+i);
    return 0;
}

我得到错误

in function `main':
dyn_array.cpp:(.text+0x1e): undefined reference to `operator>>(std::istream&, Array<int>&)'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

标签: c++arraystemplatesfriend

解决方案


您的friend声明引用了一个非模板operator>>,它与模板的定义不匹配。

friend进行引用模板的声明operator>>,例如

// forward declaration for the class template
template<class Type>
class Array;
// declaration
template<class Type>
istream& operator >> (istream& s, Array<Type>& arr);

然后

template<class Type>
class Array{
    // friend declaration
    friend istream& operator >> <Type> (istream& s, Array<Type>& arr);
    //                          ^^^^^^
    //                  or just <> (make use of template argument deduction)
    ...
};

// definition
template<class Type>
istream& operator >> (istream& s, Array<Type>& arr) {
    ...
}

或者正如Remy Lebeau 评论的那样,保留operator >>为非模板,并在类定义中定义它。

template<class Type>
class Array{
    ...
    friend istream& operator >> (istream& s, Array<Type>& arr) {
        ...
    }
};

推荐阅读