rvalue中的代理类 - 如何实现赋值运算符?

时间:2016-10-07 23:09:09

标签: c++ proxy-pattern

假设我有一个简单的向量类,其中元素通过代理类访问。

Vector class:

class vec {
public:
    vec(int len) {
        length = len;
        data = new double [len];
    }

    proxy operator[](int i) {
        if (i >= 0 && i < length) {
            return proxy(i, data);
        }
        else {
            std::cerr << "AHHHH!\n";
            exit(1);
        }
    }
private:
    int length;
    double * data;
};

代理类:

class proxy {
public:
    proxy(int i, double * d) {
        index = i;
        data  = d;
    }

    void operator=(double rhs) {
        data[index] = rhs;
    }

private:
    int index;
    double * data;
};

如何将向量(或更确切地说,从代理)中的元素分配给double类型的变量?换句话说,我如何完成以下操作:

int main() {
    vec a(2);
    double x = 3.14;
    a[0] = x; // Works!
    x = a[0]; // How to make work?

    return 0;
}

不幸的是,我不能写出类似的东西:

friend double operator=(double & lhs, const proxy & p) { ... }

因为operator=必须是会员。

1 个答案:

答案 0 :(得分:1)

向代理类添加转换函数:

"Unable to find opencart.Category with id 0; nested exception is javax.persistence.EntityNotFoundException: Unable to find opencart.Category with id 0"