[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
const int SIZE = 3;
class atype {
int a[SIZE];
public:
atype() {
register int i;
for (i = 0; i < SIZE; i++) a = i;
}
int &operator[](int i) {return a;}
};
int main()
{
atype ob;
cout << ob[2] << endl;
ob[2] = 18; //ob[2] 放在运算符 = 的左边
cout << ob[2] << endl;
return 0;
}
[C++] 纯文本查看 复制代码
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 3;
class atype {
int a[SIZE];
public:
atype() {
register int i;
for (i = 0; i < SIZE; i++) a = i;
}
int &operator[](int i);
};
int &atype::operator[](int i)
{
if(i < 0 || i > SIZE-1) {
cout << "\nIndex value of ";
cout << i << " is out-of-bounds.\n";
exit(EXIT_FAILURE);
}
return a;
}
int main()
{
atype ob;
cout << ob[2] << endl;
ob[2] = 18;
cout << ob[2] << endl;
ob[3] = 44; //产生运行时错误,下标3超出数组边界
return 0;
}
[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
class three_d {
int x, y, z;
public:
three_d() { x = y = z = 0; }
three_d(int i, int j, int k) { x = i; y = j; z = k; }
three_d operator()(int a, int b, int c);
void show();
};
//重载运算符()
three_d three_d::operator()(int a, int b, int c)
{
three_d temp;
temp.x = x + a;
temp.y = y + b;
temp.z = z + c;
return temp;
}
void three_d::show()
{
cout << x << ", ";
cout << y << ", ";
cout << z << "\n";
}
int main()
{
three_d ob1(1, 2, 3), ob2;
ob2 = ob1(10, 11, 12); //调用 operator() 函数
cout << "ob1: ";
ob1.show();
cout << "ob2: ";
ob2.show();
return 0;
}