Tar*_*aru 1 c++ templates class operator-keyword
作为练习我正在制作模板Array类,我想执行此操作:
Array<int> a[5];
a[4] = 2;
Run Code Online (Sandbox Code Playgroud)
我怎么写这样的东西?
我试过了:
template<class T> class Array{
...
T operator[(const int loc)]=(const T temp);
Run Code Online (Sandbox Code Playgroud)
你写了一个operator []返回对元素的引用.作为参考,它可以分配给via =.
template <typename T>
class Array {
…
T& operator [](unsigned int const loc) {
…
}
};
Run Code Online (Sandbox Code Playgroud)
(const参数中的参数不常用,但继续在函数的定义中使用它 - 但是,在它的声明中没有意义.)
您通常需要另一个版本操作符const,以便您仍然可以从const数组中读取值:
Array<int> x;
Array<int> const& y = x;
std::cout << y[0]; // Won’t compile!
Run Code Online (Sandbox Code Playgroud)
要使最后一行编译,请将以下代码添加到您的类:
T const& operator [](unsigned int const loc) const {
…
}
Run Code Online (Sandbox Code Playgroud)
请注意,返回值以及函数本身都标记为const.