我有一个包含预测数组的安全类 - 预测是一个类,它只包含一个双精度数。
我想允许更改双精度值,但只允许正值,
当尝试读取双精度值时,如果该值未初始化(在我的代码中等于 -1),则会抛出异常。
我也有双运算符
像这样的东西:
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;
我在哪里定义阅读和写作,因为阅读和写作时我在做不同的事情。
THANKS
你不能这样做operator[]
。操作员无法知道将如何使用它返回的值。因此,您必须将其作为返回对象的函数来执行。通过引入返回对象的赋值运算符,您可以很容易地处理对负值的赋值。
Prediction::operator=(const double value){
if (value < 0)
throw something;
...
}
如果您希望抛出此语句:
double a = predArray[0];
您必须在转换为双运算符时执行此操作。
Prediction::operator double() const {
if (value < 0)
throw something;
return value;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)