我做了一個類,其中包含一個整數數組的數組。從主函數中,我試圖在Array中使用[]獲取數組元素,就像我們在main中聲明的數組一樣。我像下面的代碼那樣重載了operator [];第一功能返回的左值和第二右值(構造器和其它部件的功能未示出。)C++運算符重載[]左值和右值
#include <iostream>
using namespace std;
class Array {
public:
int& operator[] (const int index)
{
return a[index];
}
int operator[] (const int index) const
{
return a[index];
}
private:
int* a;
}
然而,當我嘗試調用從主這兩個函數,僅第一功能,即使當訪問該變量不被用作左值。如果僅僅通過使用左值函數就可以處理所有事情,我就無法看到爲右值創建單獨的函數。
下面的代碼是我使用的主要功能(操作員< <適當超載。):
#include "array.h"
#include <iostream>
using namespace std;
int main() {
Array array;
array[3] = 5; // lvalue function called
cout << array[3] << endl; // lvalue function called
array[4] = array[3] // lvalue function called for both
}
有什麼辦法,我可以叫右值函數?是否有必要爲左值和右值定義函數?
運算符可能應該聲明爲返回'int&'和'const int&'而不是'Array'。 –
是的,你是對的。我的不好 – HelperKing