Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 两个相同的重载运算符[]一个返回引用_C++_Operator Overloading - Fatal编程技术网

C++ 两个相同的重载运算符[]一个返回引用

C++ 两个相同的重载运算符[]一个返回引用,c++,operator-overloading,C++,Operator Overloading,我可以在同一个类中使用两个重载运算符[]吗 当我使用运算符[]时,我不知道使用了哪个定义,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; }

我可以在同一个类中使用两个重载运算符[]吗

当我使用运算符[]时,我不知道使用了哪个定义,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;
};

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

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

您必须知道,顶级常量对 可以传递给函数的对象。具有顶级常量的参数为 无法与没有顶级常量的对象区分:

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

// 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的转换,所以我们可以调用 函数或指向非常量的指针。但是,当我们传递 非ST对象或指向非ST的指针。
《初级读本》中的示例。

这是否回答了您的问题?他们不是有相同的签名吗?不。一个是常量方法,另一个不是。在常量方法中,这是常量。这不完全是怎么回事,但它应该足够接近,足以让你看到区别:t&运算符[]int i是某种t&运算符[]ArrayTP*这个,int i和t运算符[]int i const是某种t运算符[]const ArrayTP*这个,int ii在我的问题中,我们总是使用整数来访问数组的元素,那么两个[]的需要是什么呢运算符声明?@aayusneupane一个运算符允许对存储在非常量ArrayTP对象中的值进行读/写访问。另一个操作符允许对存储在const ArrayTP objectOfc!中的值进行只读访问!作为一个,它是const类型的,所以它不会让你通过它来写。嗯,我有一个建议,要看一本好书。