本文介绍了为什么下标运算符C ++经常成对出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在定义模板容器 Matrix 以避免棘手的 删除代码。教程说,下标运算符经常成对出现?为什么会这样?

C++ FAQ is defining a template container Matrix to avoid tricky new delete code. Tutorial says that subscript operators often come in pairs ? Why is it so ?

T&       operator() (unsigned i, unsigned j);
T const& operator() (unsigned i, unsigned j) const;

为什么会这样?

也称为:const重载。

This is also called : const-overloading.

常见问题提供线索。

特别的,应该 mutate()遵守某些规则,只有对象?

In particular, should mutate() observe certain rules to be used safely on const objects only ?

推荐答案

T& 对象上调用下标运算符,第一个非const运算符被调用。然后,允许检查和mutate操作。

Call of subscript operator on a T& object, first non-const operator is called. Then, inspect and mutate operations are allowed.

T const& 对象上调用下标运算符,调用第二个const运算符。然后,允许检查,但不允许变异。

Call of subscript operator on a T const & object, second const operator is called. Then, inspect is allowed, but mutate is not allowed.

示例在此处

void f(MyFredList const& a)  ← the MyFredList is const
{
  // Okay to call methods that DON'T change the Fred at a[3]:
  Fred x = a[3];
  a[3].inspect();

  // Error (fortunately!) if you try to change the Fred at a[3]:
  Fred y;
  a[3] = y;       ← Fortunately(!) the compiler catches this error at compile-time
  a[3].mutate();  ← Fortunately(!) the compiler catches this error at compile-time
}

C ++常见问题,更多。

Credits to C++ FAQ, more here.

这篇关于为什么下标运算符C ++经常成对出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:56