模板操作符[]=
Template Operator []=
本文关键字:操作符 更新时间:2023-10-16
作为练习,我正在制作一个模板数组类,我想执行以下操作:
Array<int> a[5];
a[4] = 2;
我怎么写这样的东西?
我试过:
template<class T> class Array{
...
T operator[(const int loc)]=(const T temp);
您编写一个operator []
,它返回对该元素的引用。作为一个引用,它可以通过=
被赋值。
template <typename T>
class Array {
…
T& operator [](unsigned int const loc) {
…
}
};
(参数中的const
不常用,但可以在函数定义中使用它-然而,在其声明中它没有意义。)
您通常需要另一个版本操作符是const
,因此您仍然可以从const
数组读取值:
Array<int> x;
Array<int> const& y = x;
std::cout << y[0]; // Won’t compile!
要编译最后一行,请将以下代码添加到您的类中:
T const& operator [](unsigned int const loc) const {
…
}
注意,返回值和函数本身都被标记为const
。
相关文章:
- 为什么map有操作符[],set没有
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- c++新操作符通过libstdc++占用大量内存(67MB)
- 复制/移动操作符是否可以安全地用于实现复制/移动分配操作符
- 提升::精神::因果报应使用有条件的替代操作符(|)
- 促进几何体操作符
- 如果操作符delete没有实现,为什么不编译它
- 在使用放置新操作符时,我真的需要担心对齐问题吗
- 我怎样才能让getline操作符工作
- 在重载的全局new操作符中使用静态对象会导致核心转储运行时错误
- 提升ipc new和delete操作符
- 在c++中使用new操作符动态分配数组
- 操作符的大小在C++
- 如何将向量中的对象传递给操作符
- 一个更容易的拷贝分配操作符实现
- 如何重写复杂的c++代码行(嵌套的三元操作符)
- boost::make_shared没有调用(放置)操作符new
- 新操作符(以及malloc)无法分配~450MB的内存
- 类、异常和操作符
- 当delete操作符释放内存时,我为什么需要析构函数