什么是C ++中的代理类 [英] What is Proxy Class in C++
问题描述
我想知道什么是C ++中的代理类,为什么它被创建和它是有用的。
I wanted to know What is Proxy Class in C++, why it is created and where it is useful.
提前多谢。
推荐答案
代理是一个为另一个类提供修改的接口的类。这里是一个例子 - 假设我们有一个数组类,我们只想要能够包含二进制digist 1或0.这是第一次尝试:
A proxy is a class that provides a modified interface to another class. Here is an example - suppose we have an array class that we we only want to be able to contain the binary digist 1 or 0. Here is a first try:
struct array1 {
int mArray[10];
int & operator[]( int i) {
/// what to put here
}
}; `
我们希望operator []如果我们说像[1] = 42,这是不可能的,因为操作符只看到数组的索引,而不是存储的值。
We want operator[] to complain if we say something like a[1] = 42, but that isn't possible because the operator only sees the index of into the array, not the value being stored.
我们可以使用代理来解决这个问题:
We can solve this using a proxy:
#include <iostream>
using namespace std;;
struct aproxy {
aproxy( int & r ) : mPtr( & r ) {}
void operator = ( int n ) {
if ( n > 1 ) {
throw "not binary digit";
}
*mPtr = n;
}
int * mPtr;
};
struct array {
int mArray[10];
aproxy operator[]( int i) {
return aproxy( mArray[i] );
}
};
int main() {
try {
array a;
a[0] = 1; // ok
a[0] = 42; // throws exception
}
catch( const char * e ) {
cout << e << endl;
}
}
代理类现在检查二进制数字我们使数组的operator []返回一个代理的实例,它对数组的内部访问有限。
The proxy class now does our checking for a binary digit and we make the array's operator[] return an instance of the proxy which has limited access to the array's internals.
这篇关于什么是C ++中的代理类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!