[英]does overloading array operator need the assignment operator and the stream operators to be overloaded to use them in the main?
#include <iostream>
using namespace std;
class A
{
public:
int operator [] (int);
private:
int LIST [];
};
int A::operator [] (int index)
{
return LIST[index];
}
int main()
{
A obj[3];
cin >> obj [2]; // or obj [2] = 15;
cout << obj[1];
return 0;
}
我想知道為什么我必須重載賦值和 stream 運算符才能在 main 中編寫這樣的代碼,盡管我將它們與成員 function (這是數組運算符)一起使用,而不是與獨立的 ZA8CFDE6331BD49EB62AC96F8911 一起使用。
int LIST [];
不是有效的數組聲明。 如果在編譯時就知道數組的大小,則需要顯式指定,例如: int LIST[size];
其中size
是編譯時常量。 否則,請改用std::vector
在運行時分配數組。
更重要的是, A obj[3];
是A
對象的數組,在這種情況下這不是您想要的。 您需要一個A
object 來代替,例如: A obj;
當obj
是一個數組時, obj[index]
不會調用您的operator[]
。 它只會訪問數組中指定的 object,僅此而已。 這就是為什么您必須實現額外的賦值和 stream 運算符以使顯示的代碼實際使用 object 執行操作。 要在 object 上調用您的operator[]
,您首先需要訪問唯一的 object,而不是對象數組。
我懷疑您想將3
從main()
傳遞到A
以分配A::LIST
成員。 如果是這樣,試試這個:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
A(int);
int& operator [] (int);
private:
vector<int> LIST;
};
A::A(int count) : LIST(count) {}
int& A::operator [] (int index)
{
return LIST[index];
}
int main()
{
A obj(3);
cin >> obj[2]; // or: obj[2] = 15;
cout << obj[1];
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.