{ float f[3];
public:
massiv(float i,float j,float k){f[0]=i; f[1]=j; f[2]=k;}
float operator[](int i)
{ return f[i];} // []
};
int main()
{ massiv ff(1,2,3);
double f;
int i;
cout << " ";
cin >> i;
cout <<"f["<< i <<" ]= " << ff[i] << endl;
return 0;
}
operator[]() , . [] , . , operator[]() , .
#include <iostream>
using namespace std;
Class massiv
{ float f[3];
public:
massiv(float i,float j,float k){f[0]=i; f[1]=j; f[2]=k;}
float &operator[](int i) // []
{ if(i<0 || i>2) //
{ cout << <<endl;
exit(1);
}
return f[i];
}
};
int main()
{ massiv ff(1,2,3);
int i;
cout << " ";
cin >> i;
cout <<"f["<< i <<" ]= " << ff[i] << endl;
ff[i]=5; // operator , -
// =': left operand must be l-value
cout <<"f["<< i <<" ]= " << ff[i] << endl;
return 0;
}
, operator , . .
Class massiv
{ float f[3];
public:
...
float *operator[](int i) // []
{ ...
return &f[i];
}
};
int main()
{ massiv ff(1,2,3);
...
*ff[i]=5; // operator
cout <<"f["<< i <<" ]= " << *ff[i] << endl;
return 0;
}
, ff . .
, operator[].
// operator[] n!
#include <iostream>
using namespace std;
#include "values.h" // MAXLONG
Class fact
{ long l;
public:
long operator[](int); // []
};
long fact::operator[](int n)
{ long l;
for (int i=0; i<=n; i++) //
if(l>MAXLONG/i)
cerr<<" "<<n<<" "<<MAXLONG;
else l*=i;
return l;
}
int main()
{ fact f;
int i,k;
cout << " k "
cin >> k;
for (i=1; i<=k; i++)
cout << i <<"! = " << f[i] << endl;
return 0;
}