So I only recently started using "Inline operator overloading" or whatever it's called...... Anyways!! How can I refer to the object I am calling the function from. Here's the code of interest:
class PlayingCard
{
private:
enum Suit {diamond, hearts, spades, clubs};
Suit suit;
enum Color {red, black};
Color color;
int value = -1;
public:
//Inline stuff
//make card the same as c1
inline operator=(const PlayingCard &c1) {
suit = c1.suit;
color = c1.color;
value = c1.value;
return true;
}
inline operator%(PlayingCard &c1) {
PlayingCard copy1;
copy1 = c1;
c1 = this;
this = copy1;
return true;
}
As you can see I have the class PlayingCard. The first inline operator works just as it should. If I have 2 PlayingCard: c1 and c2 with the private values of c2 being defined then c1 = c2 makes the private values of c1 equal to c2.
The second inline function is meant to swap the values between c1 and c2 by doing c1 % c2. As is shown in the code I was hoping to use "this" to refer to c1 but it doesn't work. Is there a way to refer to c1 in this function?
I know there are work-arounds which I'll be using in the meantime, but I'd rather use my original method and I feel like it would be helpful for future use as well.
There is no such an operator as <->
(that you later changed to %
in the updated question) in C++. It seems you want to define a member function swap
. But in any case you may not swap constant objects. So the parameter of the function should be a non-constant reference.
Member functions defined in class definitions by default have the function specifier inline. So there is no need to explicitly specify it.
The assignment operator should return a reference to the assigned object.
Here you are.
PlayingCard & operator =( const PlayingCard &c1 )
{
if ( this != &c1 )
{
suit = c1.suit;
color = c1.color;
value = c1.value;
}
return *this;
}
void swap( PlayingCard &c1 )
{
if ( this != &c1 )
{
std::swap( suit, c1.suit );
std::swap( color, c1.color );
std::swap( value, c1.value );
}
}