什么是C ++中的代理类 [英] What is Proxy Class in C++

查看:117
本文介绍了什么是C ++中的代理类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的代理类是什么?为什么它被创建,它在哪里有用?

解决方案

代理是一个类,为另一个类提供一个修改的接口。这里是一个例子 - 假设我们有一个数组类,我们只想要包含二进制数字1或0.这是第一个尝试:

  struct array1 {
int mArray [10];
int&运算符[](int i){
///在这里放置
}
}; `

如果我们说的是[1] = 42,我们希望operator []抱怨,但是这是不可能的,因为操作员只能看到数组中的索引,而不是存储的值。



我们可以使用代理来解决这个问题:

  #include< iostream> 
使用命名空间std;

struct aproxy {
aproxy(int& r):mPtr(& r){}
void operator =(int n){
if(n& ; 1){
thrownot 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 []返回一个对数组的内部访问有限的代理实例。


What is a Proxy Class in C++? Why it is created and where it is useful?

解决方案

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 only want to be able to contain the binary digits 1 or 0. Here is a first try:

struct array1 {
    int mArray[10];
    int & operator[](int i) {
      /// what to put here
    }
}; `

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;
    }
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆