在C ++中使用运算符[]重载来区分读写 [英] distinguish between read and write using operator [] overloading in c++

查看:98
本文介绍了在C ++中使用运算符[]重载来区分读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一组预测的安全类-预测是一个类,只包含一个双精度类. 我想允许更改double的值,但只允许使用正值, 并尝试读取double时,如果该值未初始化(在我的代码中等于-1),则抛出异常. 我在
中也有double运算符 像这样的东西:

I got a Security Class that has an array of Predictions - Prediction is a Class, which holds only a double. I want to allow changing the value of the double, but allow only positive values, and when trying to read the double, if the value is uninitialized (equals -1 in my code) throw exception. I also have double operator in
Something like that:

class Prediction{
    double value;
public:
    .....
    Prediction::operator double() const {
        return this->prediction;
    }
    Prediction::operator=(const double value){
       ...
        //check value
    }

}

class Security{
   ...
    Prediction& Security::operator[](int index){
        return predArray[index];
    }
}

Prediction *predArray = new Prediction[4];
//default constructor set the value -1;

double a = predArray[0] //should throw an exception, because predArray[0] = -1
predArray[0] = 4; //should be O.K. because I want to change the value
predArray[1] = -4; //should throw exception, because trying to put negative value;

我在读写之间定义的位置,因为在读写时我做的是不同的事情.

where do I define between reading and writing, because I'm doing different things when reading and writing.

谢谢

推荐答案

您不能在operator[]中执行此操作.操作员无法知道将如何使用它返回的值.因此,您必须根据返回的对象来执行此操作.通过抛出返回对象的赋值运算符,您可以轻松地将赋值处理为负值.

You cannot do that in operator[]. There's no way for the operator to know how the value it returns is going to be used. So you have to do this as a function of the returned object. You can handle the assignment to a negative value easy enough, by throwing in the assignment operator of the returned object.

Prediction::operator=(const double value){
    if (value < 0)
        throw something;
    ...
}

如果您希望此语句抛出:

If you want this statement to throw:

double a = predArray[0];

在转换为double运算符时,您必须这样做.

You will have to do that in your conversion to double operator.

Prediction::operator double() const {
    if (value < 0)
        throw something;
    return value;
}

这篇关于在C ++中使用运算符[]重载来区分读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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