您需要創建一個Proxy類來替代兩個方法的返回值。然後,在Proxy類中,您可以適當地處理讀取和寫入操作。這裏的代碼應該編譯驗證這個想法(與無符號整數數組工作):
typedef unsigned int UINT;
類A {
class Proxy {
public:
Proxy(const UINT &number): _number(number) {}
const Proxy &operator=(const Proxy &obj) {
cout << "Writting...\n";
_number = obj._number;
return *this;
}
operator const UINT &() const {
cout << "Reading...\n";
return _number;
}
private:
UINT _number;
};
市民:
A(UINT *array): _array(array) {}
Proxy operator[](int index) {
return _array[index];
}
const Proxy operator[](int index) const {
return _array[index];
}
私人:
UINT *_array;
};
INT主(INT ARGC,字符**的argv){
UINT myArray[] = {0, 1, 2, 3, 4};
A a(myArray); // Normal A object
UINT num1 = a[1]; // Reading fine
a[1] = num1; // Writting fine
const A ca(myArray); // Constant A object
UINT num2 = ca[1]; // Reading fine
ca[1] = num2; // Writting NOT fine (compilation error)
return 0;
}
如果您允許人們保存返回的參考資料並在以後使用,那麼您必須在返回參考資料後禁用將來的共享。 – 2011-04-29 14:13:38