两个相同的重载操作符[]一个返回引用。

问题描述 投票:0回答:1

我可以有两个超载 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;
};

这个类包含了这些重载操作符的声明。但我的问题中没有包含定义。

c++ operator-overloading
1个回答
1
投票

重载运算符的工作原理与普通的重载函数没有什么不同。只是它们是特殊的函数。所以我给你举一个函数的一般例子,同样适用于任何类型的函数。

你一定知道,顶层常量对可以传递给函数的对象没有影响。一个有顶层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或非const版本的引用(或指针)来重载,这种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参数的版本。因为有const的转换,所以我们可以在一个非const对象或一个指向非const的指针上调用任何一个函数。然而,当我们传递一个非const对象或指向非const的指针时,编译器会更倾向于非const版本。.引子中的例子。

© www.soinside.com 2019 - 2024. All rights reserved.