【问题标题】:Why is it not possible to overload insertion operators in c++ for a dynamic array?为什么不能在 C++ 中为动态数组重载插入运算符?
【发布时间】:2021-07-02 19:45:51
【问题描述】:

我是 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)

【问题讨论】:

  • 这并没有解决问题,但是流提取器不应该提示输入。当程序从文件中读取时,该提示将非常混乱。
  • 它还应该使用给它的流而不是硬编码cin。这个想法是你编写一个重载来支持输入,它适用于任何输入源。

标签: c++ arrays templates friend


【解决方案1】:

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

引用模板operator&gt;&gt; 进行friend 声明,例如

// 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 commented,保持operator &gt;&gt;为非模板,并在类定义中定义。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2015-11-13
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    相关资源
    最近更新 更多