在實際程式中遇到一操作符問題,記錄下來友善以後查詢。在寫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;
}