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

本文是小编为大家收集整理的关于什么是C++中的代理类的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

推荐答案

代理是一个类,它为另一个类提供修改后的接口.这是一个示例 - 假设我们有一个数组类,我们只希望能够包含二进制数字 1 或 0.这是第一次尝试:

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

如果我们说 a[1] = 42 之类的东西,我们希望 operator[] 抱怨,但这是不可能的,因为 operator 只看到数组中的索引,而不是存储的值.

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

#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[] 返回一个代理实例,该实例对数组内部的访问权限有限.

本文地址:https://www.itbaoku.cn/post/627547.html

问题描述

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.