【问题标题】:Two same overloaded operator [] one returning reference两个相同的重载运算符 [] 一个返回引用
【发布时间】:2019-11-12 02:45:55
【问题描述】:

我可以在同一个班级中有两个像这样重载的operator[]吗?

当我使用operator[] 时,我对使用哪个定义感到困惑,int 不是模棱两可吗?他们不是有相同的签名吗?

template <class T, int n> 
class ArrayTP 
{ 
private: 
    T ar[n]; 
public: 
    ArrayTP() {};

    virtual T & operator[](int i); 
    virtual T operator[](int i) const;
};

此类包含这些重载运算符的声明。不过,我的问题中没有包含定义。

【问题讨论】:

  • "他们不是有相同的签名吗?" 没有。一个是const方法,另一个不是。
  • const 方法中thisconst。这不是正在发生的事情,但它应该足够接近以向您展示差异:T &amp; operator[](int i) 有点像 T &amp; operator[](ArrayTP * this, int i)T operator[](int i) const 有点像 T operator[](const ArrayTP * this, int i)

标签: c++ operator-overloading


【解决方案1】:

重载运算符的工作方式与正常的重载函数没有什么不同。只是它们是特殊功能。所以我给你的函数的一般例子同样适用于任何类型的函数。

您必须知道,顶级 const 对 可以传递给函数的对象。具有顶级 const 的参数是 与没有顶级 const 的没有区别:

Record lookup(Phone);
Record lookup(const Phone); // redeclares Record lookup(Phone)
Record lookup(Phone*);
Record lookup(Phone* const); // redeclares Record lookup(Phone*)

在这些声明中,第二个声明与第一个声明相同的功能。 另一方面,我们可以根据参数是否为引用来重载 (或指针)指向给定类型的 const 或 nonconst 版本;这样的常量是 低级。

// functions taking const and nonconst references or pointers have different parameters 
// declarations for four independent, overloaded functions
Record lookup(Account&); // function that takes a reference to Account
Record lookup(const Account&); // new function that takes a constbreference.
Record lookup(Account*); // new function, takes a pointer to Account
Record lookup(const Account*); // new function, takes a pointer to const

在这些情况下,编译器可以使用参数的常量来区分 调用哪个函数。 因为没有从 const 转换, 我们只能将 const 对象(或指向 const 的指针)传递给带有 常量参数。因为有一个到 const 的转换,我们可以调用 非常量对象或指向非常量的指针上的函数。然而,当我们传递一个 非常量对象或指向非常量的指针。 引子中的例子。

【讨论】:

  • 在我的问题中,我们总是使用整数来访问数组的元素,那么两个 [] 运算符声明需要什么?
  • @AAYUSHNEUPANE 一个运算符允许对存储在非常量 ArrayTP 对象中的值进行读/写访问。另一个运算符允许对存储在 const ArrayTP 对象中的值进行只读访问
  • Ofc !作为一个,它是 const 类型,所以它不会让你写完它。好吧,我有一个建议,可以阅读一本好书。 stackoverflow.com/questions/388242/…
猜你喜欢
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 2013-06-01
  • 1970-01-01
相关资源
最近更新 更多