C++ 中的代理類是什麼?
接下來,我們將瞭解 C++ 中的代理類是什麼。基本上代理類就是代理設計模式。在此模式中,一個物件為另一個類提供修改後的介面。下面我們來看一個例子。
在此示例中,我們希望建立一個數組類,該陣列類僅能儲存二進位制值 [0,1]。如下是第一次嘗試。
示例程式碼
class BinArray {
int arr[10];
int & operator[](int i) {
//Put some code here
}
};在此程式碼中,沒有條件檢查。但我們希望在將 arr[1] = 98 之類的內容放入陣列時,operator[] 會報異常。不過這不可能,因為它正在檢查索引而不是值。現在我們嘗試使用代理模式解決此問題。
示例程式碼
#include <iostream>
using namespace std;
class ProxyPat {
private:
int * my_ptr;
public:
ProxyPat(int& r) : my_ptr(&r) {
}
void operator = (int n) {
if (n > 1) {
throw "This is not a binary digit";
}
*my_ptr = n;
}
};
class BinaryArray {
private:
int binArray[10];
public:
ProxyPat operator[](int i) {
return ProxyPat(binArray[i]);
}
int item_at_pos(int i) {
return binArray[i];
}
};
int main() {
BinaryArray a;
try {
a[0] = 1; // No exception
cout << a.item_at_pos(0) << endl;
}
catch (const char * e) {
cout << e << endl;
}
try {
a[1] = 98; // Throws exception
cout << a.item_at_pos(1) << endl;
}
catch (const char * e) {
cout << e << endl;
}
}輸出
1 This is not a binary digit
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP