proxy class in rvalue - how to implement assignment operator?

99封情书 提交于 2019-12-25 08:26:29

问题


Suppose I have a simple vector class where elements are accessed through a proxy class.

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

Proxy class:

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

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

private:
    int index;
    double * data;
};

How can I assign elements from the vector (or rather, from the proxy) to a variable of type double? In other words, how do I accomplish the following:

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

    return 0;
}

Unfortunately, I can't write something like:

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

since operator= must be a member.


回答1:


Add a conversion function to your proxy class:

class proxy
{
public:
    operator double() const { return data[index]; }

    // ...
};


来源:https://stackoverflow.com/questions/39926941/proxy-class-in-rvalue-how-to-implement-assignment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!