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