Reputation: 2732
I don't know whether what I'm about to ask depends from the tool I'm using or from the language itself but anyway.
I have a situation where I have "one method" declared several times with different signature. Such as:
class my_class {
public:
int getData();
int getData() const;
my_class operator+(my_class&,my_class&);
my_class operator+(const my_class&, const my_class&) const;
//other operators, other functions etc with similar feature
private:
int data;
};
As you can imagine the implementation would be always the same, it's just the signature the issue. Is there a way to avoid to write two times the same implementation of such functions?
At the beginning I thought a casting from the type to const type would have been performed, but apparently I was wrong.
Thank you
Upvotes: 0
Views: 63
Reputation: 170153
Your overloads aren't declared properly. A class member binary operator can take only one parameter, the other is implicitly this
. Otherwise you can't use it with infix notation.
You don't need both overloads. The operator shouldn't change the operands, so the const version alone is enough.
So that leaves us with:
class my_class {
public:
int getData();
int getData() const;
my_class operator+(const my_class&) const;
//other operators, other functions etc with similar feature
private:
int data;
};
Or the non-member version:
class my_class {
public:
int getData();
int getData() const;
friend my_class operator+(const my_class&, const my_class&);
//other operators, other functions etc with similar feature
private:
int data;
};
my_class operator+(const my_class&, const my_class&) {
// code
}
As for getData()
. It retunsa copy of your data, and I assume it doesn't modify the instance. Then the const
overload is also enough.
Upvotes: 1