Reputation: 1573
In the code below I am trying to overload the =
operator of int
. So that I could support int A= &d
statements in my program.
class Data{
public:
int a;
Data(int A): a(A) {}
operator int() {return a;}
};
int operator=(int &lhs, Data* rhs){
lhs = rhs->a;
return lhs;
}
int main(){
Data d(10);
int A = &d;
return 0;
}
But it's giving compile time error:
error: ‘int operator=(int&, Data*)’ must be a nonstatic member function int operator=(int &lhs, Data* rhs){
test1.cpp: In function ‘int main()’:
test1.cpp: error: invalid conversion from ‘Data*’ to ‘int’ [-fpermissive] int A = &d;
Please suggest me the right way of overloading the operator.
Upvotes: 2
Views: 274
Reputation: 8238
You do not need assignment operator (operator=
) overload in your class. Moreover, it cannot take two arguments.
All you need is cast operator (your operator int() {return a;}
) and a proper assignment like int A = d;
. When you write &
before d
, you put address of d
into A
if int
is wide enough to store pointers on your system.
Upvotes: 0
Reputation: 41301
You can't overload an assignment to int
. As the compiler tells you, operator=
has to be a non-static member function of a class, end of story.
You already have the conversion to int
in your class, so you can write int A = d;
.
Upvotes: 2