Operator overload assignment

Hello

I have a class called Piece, defined as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Piece
{
private:
    e_pieces type;              // type of piece (EMPTY if no piece placed)
    bool winning;               // true if piece was the winning move
    bool player;                // true = player 1, false = player 2

public: 
	
Piece();
~Piece();
Piece & operator=(const e_pieces &rhs);		
e_pieces operator=( const Piece &rhs );
etc.

}; // endof class Piece 


and implimented as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Piece::Piece()
{
    type=EMPTY;
    player=false;
    winning=false;
}
Piece::~Piece()
{
};

Piece & Piece::operator=(const e_pieces &rhs)
{
	type=rhs;
	return *this;
}

e_pieces Piece::operator=( const Piece &rhs ) 
{
	return rhs.type;
}


The first assignment operator override works correctly, e.g.:
1
2
board = new Piece[Places];            
board[0]=EMPTY;


This assigns the prviate "type" inside the class as EMPTY. But how do I access this through operator override?

I have tried as above but get a compile error - I want to be able to say:
1
2
e_pieces temp; 
temp=board[0]


What am I doing wrong?

Thanks

Nick
You overloaded operator = (Piece, e_pieces); and now you have to overload operator = (e_pieces, Piece);
Hi - thanks! I have tried to do this in:

1
2
3
4
e_pieces Piece::operator=( const Piece &rhs ) 
{
	return rhs.type;
}


but when I try the assignment like: temp=board[0], the compiler complains:

error C2440: 'initializing' : cannot convert from 'demo::Piece' to 'e_pieces'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called


It appears that I can do board[0]=<e_pieces> but not the reverse?
When you declare an operator as a member function, the first parameter is Piece and is on the left side. If you want to have it on the right side, declare a global operator + (e_pieces, Piece).
Hi

I have made it a gloabal:

friend e_pieces operator=( const Piece &rhs );

But I get an error "operator= must be a member function"

It seems to be fine with operators such as "+" or "-" but not "="??
First, your assignement operator doesn't do anything.
If you want to assign to class A, you must overload operator= in class A.

e_pieces & epieces::operator=(const Piece &rhs)

You could also make a convert operator in class B
1
2
3
Piece::operator e_pieces(){ //I'm not sure about the prototype
  return this->type;
}
So when you do
1
2
3
4
A a; B b;
a = b; 
//a = (A) b 
//e_pieces & epieces::operator=(const e_pieces &rhs) 
Last edited on
Topic archived. No new replies allowed.