在实际程序中遇到一操作符问题,记录下来方便以后查询。在写HashTable数据结构中,遇到操作符[]重载问题,具体需求如下:
1. a[x] = b; //如果a[x]为空,则添加记录
2. b = a[x]; //如果a[x]为空,则提示出错
对[]操作符重载之后发现根本不能解决问题,查找一些资料后发现该问题为重载后的读写问题,一个重载解决不了问题。上面两点展开如下:
1. a.operator[](x).opeator=(b) // A.operator=(b)
2. b.operator=(a.operator[](x)) //b.operator=(A)
将a.operator[](x)作为对象A后,问题1就成了对象A的赋值操作符重载问题,问题2就为对象A的类型转换问题。增加一个代理类就可以有效分离两种情形了,具体实现如下:
#include <iostream>
#include <vector>
using namespace std;
class A {
private:
vector<int> v;
int defnum;
public:
A(unsigned int number):defnum(-1) {
for(unsigned int i = 0; i < 10; ++i) {
v.push_back(number);
}
}
const int& operator[](const int &u) const {
cout << "operator[](const) const -- reading, u:"<< u << ",value:" << v[u] << endl;
if(v[u] == 0) return defnum;
return v[u];
}
int & operator[](const int &u) {
cout << "const operator[](const)--writing,u:"<< u << ",value:" << v[u] << endl;
return v[u];
}
};
class B {
private:
vector<int> v;
int defnum;
public:
B(unsigned int number):defnum(-1) {
for(unsigned int i = 0; i < 10; ++i) {
v.push_back(number);
}
}
private:
int read(int idx) {
if(v[idx] == 0) return defnum;
return v[idx];
}
const int& write(int idx, int value) {
v[idx] = value;
return v[idx];
}
class Proxy {
friend class B;
private:
B * const pb_;
int v_;
Proxy(): pb_(NULL),v_(0) {}
Proxy(B *pb, int idx):pb_(pb),v_(idx) {}
public:
operator int() {
cout << "reading in here" << endl;
return pb_->read(v_);
}
const int& operator = (const int &val) {
cout << "writing in here" << endl;
return pb_->write(v_, val);
}
};
public:
Proxy operator[](const int &idx) {
return Proxy(this,idx);
}
};
int main(int argc, char *argv[]) {
A a(0);
B b(0);
int value;
a[1] = 3; // writing
value = a[2]; //reading
value = 4;
cout << "a[1]:" << a[1] << ",value:"<< value << ",a[2]:" << a[2]<<endl;
b[1] = 3; // writing
value = b[2]; //reading
value = 4;
cout << "b[1]:" << b[1] << ",value:"<< value << ",b[2]:" << b[2]<<endl;
return 0;
}