什么是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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便