PBanta
January 15th, 2007, 09:09 PM
What is the difference between using "*" and"&" in operator overloading of a managed class? The two code examples below compile on my .Net compiler, but I don't know what the difference is. Would somebody explain?
Thanks,
Paul
public __gc class Complex
{
private:
float real;
float imaginary;
// . . .
public:
static Complex* op_Assign( Complex* lhs, float real )
{
// I think the code should be like this.
lhs->real = real;
lhs->imaginary = 0.0f;
return lhs;
}
} // end class Complex
Compare with the code below which uses "Complex&" in the overloaded operator. Both compile, but I suspect they are different in how they work.
public __gc class Complex
{
private:
float real;
float imaginary;
// . . .
public:
static Complex& op_Assign( Complex& lhs, float real )
{
// I think the code should be like this.
lhs.real = real;
lhs.imaginary = 0.0f;
return lhs;
}
} // end class Complex
I added code to the two methods in question. I think the code is right, but am not completely sure. I may be answering my own question. It looks like the two different signatures have some affect on the code inside the method. But more than that, I would think that the different signatures affect how the methods are called. Using the "*" operator, I think you would call it with:
Complex* c1 = new Complex;
Complex* c2;
c2 = c1 = 5.0f;
Using the "&" operator, I think you would call it with:
Complex c1;
Complex c2;
c1 = c2 = 5.0f;
Is this right? Am I close?
Thanks,
Paul
public __gc class Complex
{
private:
float real;
float imaginary;
// . . .
public:
static Complex* op_Assign( Complex* lhs, float real )
{
// I think the code should be like this.
lhs->real = real;
lhs->imaginary = 0.0f;
return lhs;
}
} // end class Complex
Compare with the code below which uses "Complex&" in the overloaded operator. Both compile, but I suspect they are different in how they work.
public __gc class Complex
{
private:
float real;
float imaginary;
// . . .
public:
static Complex& op_Assign( Complex& lhs, float real )
{
// I think the code should be like this.
lhs.real = real;
lhs.imaginary = 0.0f;
return lhs;
}
} // end class Complex
I added code to the two methods in question. I think the code is right, but am not completely sure. I may be answering my own question. It looks like the two different signatures have some affect on the code inside the method. But more than that, I would think that the different signatures affect how the methods are called. Using the "*" operator, I think you would call it with:
Complex* c1 = new Complex;
Complex* c2;
c2 = c1 = 5.0f;
Using the "&" operator, I think you would call it with:
Complex c1;
Complex c2;
c1 = c2 = 5.0f;
Is this right? Am I close?