重载运算符 [] 如何工作
How does overloading operator[] work?
struct rowDisplayPolicy
{
static std::string seperator() { return ", "; }
};
struct columnDisplayPolicy
{
static std::string seperator() { return "n "; }
};
template <typename T, int Size, typename DisplayPolicy>
class Array {
public:
Array() : pArray(new T[Size]) {}
Array(T* pT) : pArray(new T[Size])
{
for(int i=0; i<Size; ++i)
*(pArray + i) = *(pT + i);
}
~Array() { delete [] pArray; }
T& operator[](int n)
{
if(n<0 || Size<=n) throw std::Exception("index out of range");
return *(pArray+n);
}
T operator[](int n) const
{
if(n<0 || Size<=n) throw std::Exception("index out of range");
return *(pArray+n);
}
void display() const
{
std::cout << "n ";
for(int i=0; i<Size-1; ++i)
std::cout << *(pArray+i) << DisplayPolicy::seperator();
std::cout << *(pArray+Size-1) << "n";
}
private:
Array(const Array<T,Size,DisplayPolicy>&); // make public impl. Later
Array<T,Size,DisplayPolicy>& operator=(const Array<T,Size,DisplayPolicy>&); // ditto
T* pArray;
};
我有一个问题,为什么运算符[]重载两种不同的方式。 以及它们之间有什么区别。我不知道"函数((常量"的含义。你能给我举一些例子吗?
成员函数有一个隐式参数this
,尾随const
用于函数重载解析。你可以这样想:
void Array::function() -> void function( Array* this )
void Array::function() const -> void function( Array const* this )
const 在方法上意味着该方法不允许修改对象。
第一个运算符 [] 返回对 n 处元素的引用(因此允许修改数组( - 不能在 const 对象上调用它。
第二个运算符 [] 返回 n 处元素的副本。 它不会修改数组 - 并且可以在常量对象上调用。例如:
Array<int, 10> my_array1();
int test1 = my_array1[0]; // Calls first operator[]
const Array<int, 10> my_array2();
int test2 = my_array2[0]; // Calls second operator equals
这通常适用于数组作为参数传递给函数的上下文,其中它可能被限定为 const,因为它希望函数能够读取数组但不更改它。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- sdl软件渲染器不工作,工作在硬件加速的一个