struct integer
{
int x;
void set(int i)
{
this->x=i;
return;
}
int get()
{
return this->x;
}
integer operator=(integer v1)
{
integer v2;
v2.set(v1.get());
return v2;
}
};
int main(void)
{
console::clear();
integer v1,v2;
output::string("enter two number");
v1.set(input::integer());
v2.operator=(v1);
output::integer(v2.get());
output::string("=");
output::integer(v1.get());
console::pause();
return 0;
}
i just make operator function a member function and call it and its not giving the correct result
When you use the statement
v2.operator=(v1);
you do not change object v2, because inside the operator function
integer operator=(integer v1)
{
integer v2;
v2.set(v1.get());
return v2;
}
you change a temporary object that is declared as a local variable
integer v2;
The correct realization of the assignment operator looks the following way
1 2 3 4 5
|
integer & operator =( const integer &v1 )
{
set( v1.get() );
return ( *this );
}
|
Last edited on
@vald from moscow
thanx for rply it works
I have a Q?
1-> why we use ref of class as parameter for operator function can we take class vriable if not then why?
We can but in this case a copy of the object will be created. When a reference to an object is used no temporary object are created