什么是C ++中的代理类?
在这里,我们将看到什么是C++中的代理类。Proxy类基本上是Proxy设计模式。在这种模式下,对象为另一个类提供了修改后的接口。让我们来看一个例子。
在此示例中,我们要创建一个只能存储二进制值[0,1]的数组类。这是第一次尝试。
范例程式码
class BinArray {
int arr[10];
int & operator[](int i) {
//在这里放一些代码
}
};在此代码中,没有条件检查。但是,如果我们放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