|
-
May 1st, 2003, 08:07 AM
#1
what is the difference between reference and pointer
hi, buddy!I am a beginer here. thanks for your answer:
bow to everyone.
I am always confused by the reference and pointer. in the
code below I think it should return the Pointer 'this' but why
it return '*this', i think *this means the contents of the pointer.
who can help me? thanks a lot!
const Array &Array::operator =(const Array &right)
{
if(&right!=this)
{
delete [] ptr;
size = right.size;
ptr=new int[size];
assert(ptr!=0);
for(int i =0; i<size;i++)
ptr[i] = right.ptr[i];
}
return *this;
}
this function should return a const reference of Array,right?
-
May 1st, 2003, 08:51 AM
#2
Correct.
The overloaded operator returns a constant reference to an object, thus allowing code:
Object A;
Object B = A;
The overloaded operator can in theory return a pointer to the object, but that does not work with the code above.
Change this line:
if(right!=*this)
{}
Kuphryn
-
May 1st, 2003, 09:17 AM
#3
Originally posted by kuphryn
Correct.
The overloaded operator returns a constant reference to an object, thus allowing code:
Object A;
Object B = A;
The overloaded operator can in theory return a pointer to the object, but that does not work with the code above.
Change this line:
if(right!=*this)
{}
Kuphryn
thanks for you reply.
i think if(&right!=this) and if(right!=*this) will have the same effect. the code i paste above is a sample code of a book.i
have tested it. it's correct code. what i want to know is why
not return this but return *this.
-
May 1st, 2003, 09:19 AM
#4
Originally posted by wenjiahe
what i want to know is why
not return this but return *this.
Because 'this' is a pointer to the object and '*this' is the actual object. Since the operator will return a reference to the object and not the pointer you have to return the latter one...
-
May 1st, 2003, 09:26 AM
#5
Originally posted by Andreas Masur
Because 'this' is a pointer to the object and '*this' is the actual object. Since the operator will return a reference to the object and not the pointer you have to return the latter one...
ok, you mean reference to an object equal the object itself,right?
-
May 1st, 2003, 09:34 AM
#6
Originally posted by wenjiahe
ok, you mean reference to an object equal the object itself,right?
Correct...a reference can be seen as a transparent way of looking to the object itself...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|