两个相同的重载运算符[]

时间:2019-11-12 02:45:55

标签: c++ operator-overloading

我可以在同一个班级有两个这样的重载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;
};

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

1 个答案:

答案 0 :(得分: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版本;这样的const是 低级的。

// 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参数。由于存在向const的转换,因此我们可以调用 非常量对象上的函数或指向非常量的指针。但是,当我们传递一个  非常量对象或指向非常量的指针。 引物中的例子。