Hey ya'll. I'm having a problem trying to overload the = operator in Visual C++ (C++.Net). This is what I have for my code right now in my class:
Book^ operator=(Book^ value) {
Book^ b = gcnew Book();
if ( value ) {
b-%26gt;AuthorFirst = value-%26gt;AuthorFirst;
b-%26gt;AuthorLast = value-%26gt;AuthorLast;
b-%26gt;ISBN = value-%26gt;ISBN;
b-%26gt;Publisher = value-%26gt;Publisher;
b-%26gt;Price = value-%26gt;Price;
}
return b;
}
Book is the class I created. I'm trying to make it so when I type bookOne = bookTwo it will copy the values from bookTwo to bookOne, but not create a reference to bookTwo. Right now, it's creating that reference. When I try to change a value on the bookOne object, the values on bookTwo change also.
Any help would be greatly appreciated, thanks!
VC++ Operator Overload?
I think you should try instead of using b to just use the "this" pointer and return "*this". Or maybe try returning "*b" instead of just the pointer to b.
Also, I think the reason that an update to one reference updates them both is that your operator is not being called. So if you do this:
Book* b1(...);
Book* b2(...);
b1 = b2;
this will not call your operator because b1 is a pointer. It will copy the address of b2 into b1, and taht's why they refer to the same thing afterwards. Your operator is a member of the *class*, not a pointer to the class. In order for your operator to be called, you'd have to call it like this:
*b1 = b2;
You have to use b2 and not *b2 because your argument to operator= is Book*. Obviously this is not how operator= is meant. You should change its argument to Book%26amp; so you can say this:
*b1 = *b2;
which means to copy one book value to the other.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment