i have a certain class and i want to create 2 operators that will work together
like class with array and i want to change a certain index in the array
like this obj[3]=5
is this possible? if yes,how?
this is the code i made for [] operator
double Polynomial::operator[](int index) const {
int maxT = this->currentMax;
if (index > 0 && index < this->getDegree(false))
return this->coefficients[index];
cout << "overflow in index";
system("pause");
}
Your operator[]
is a const
method, hence it cannot be used to modify members. Unless you want to do something fancy on assigning to an element, you don't really need some operator=
when your operator[]
returns a reference to the element.
As mentioned in comments, doing bounds-checking in operator[]
is not typical. Consider that in a loop each call to operator[]
would do bounds-checking even if the user made sure that only valid indices are used. Thats not quite efficient. So in addition to your const
operator you can provide this one
double& Polynomial::operator[](size_t index) { // <-- no const
return coefficients[index];
}
Assuming you also have a size
method you can then write a loop:
for (size_t i=0; i< poly.size(); ++i) {
poly[i] = i;
}
PS: system("pause")
is a no-go, see system("pause"); - Why is it wrong?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.