I’m trying to create an overridden operator function using both const parameters, but I can’t figure out how to do it. Here is a simple example:
class Number { Number() { value = 1; }; inline Number operator + (const Number& n) { Number result; result.value = value + n.value; return result; } int value; }
What I am trying to do here is pass in two arguments into the addition function that are both const and return the result without changing anything in the class:
const Number a = Number(); const Number b = Number(); Number c = a + b;
Is this possible and how would I go about doing this?
Thanks,
Dan
inlineis understood in class declarations so you don’t need to specify it.Most idiomatically, you would make
operator+a non-member function declared outside the class definition, like this:You might need to make it a
friendof the class if it needs access toNumber‘s internals.If you have to have it as a member function then you need to make the function itself const:
For classes like
Number,operator+is typically implemented in terms ofoperator+=as usually you want all the usual operators to work as expected andoperator+=is typically easier to implement andoperator+tends not to lose any efficiency over implementing it separately.Inside the class:
Outside the class:
or even: