c++ - 为什么不能在 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)
解决方案
您的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) {
...
}
};
推荐阅读
- python - 在排序一个列表期间将不同列表中的相关元素保持在一起
- c# - 如何对通用列表对象进行排序
- javascript - 向和从 js 服务器发送数据的基本方法?
- json - 使用 Pyspark 处理 JSON 结构
- amazon-web-services - 为什么角色假设应该在 lambda 内部完成?
- html - 如何将数值绑定到 CSS 以创建时间线?
- docker - 如何为 docker compose 环境变量设置运行时变量
- javascript - 仅在 Javascript 中具有不同段落的动态 Div
- tsql - 表格模型中的测量列未在浏览器中显示正确的值
- javascript - 调用此函数时如何获取返回值?