給出一個簡單的類,重載 '[]' 操作員工作:與運營商[]和operator =
class A
{
public:
int operator[](int p_index)
{
return a[p_index];
}
private:
int a[5];
};
我想完成以下任務:
void main()
{
A Aobject;
Aobject[0] = 1; // Problem here
}
我怎麼能過載在這種情況下,賦值'='操作符與'[]'操作符一起使用?
+1。另外,你可能想要在const上重載:'int operator [](int p_index)const' – 2010-05-04 15:53:49
在const版本中,你可以返回一個普通的'int'而不是'const int&'。 – 2010-05-04 16:08:19
@David,如果你想接受它的地址,這可能不是一個好主意。 'foo = &a[0];'被'a'爲常量'A'。 – 2010-05-04 16:37:27