Sep 15, 2011 at 9:14am UTC
Hi,
Im learning the c++ object and structure and operator
A few question:
1. how do you copy the structure address to the operator overload (equal)
struct MyStruct
{
char Name[50];
struct MyStruct *next;
}
class MyClass
{
MyClass();
void Add(MyStruct*);
MyClass operator=(MyClass &);
MyStruct * Head;
}
MyClass::MyClass
:Head(NULL)
{
}
void Add(MyStruct* Add)
{
MyStruct* Entry = new MyStruct;
Entry = Add;
Entry->next = Head;
Head = Entry;
}
MyClass MyClass::operator=(const MyClass ©)
{
// how can we copy the pointer and return it
}
// main
MyClass* A = new MyClass();
MyClass B; // copied here
MyStruct* Data;
Data = new MyStruct;
strcpy(Data->Name,'first name');
A->Add(Data);
Data = new MyStruct;
strcpy(Data->Name,'Second name');
A->Add(Data);
B=A;
I hope the above example code can help to explain what im trying to achieve
Sep 15, 2011 at 10:08am UTC
You should call that one "assignment" operator. "Equals" would be == in C++. You can't use operators directly with pointers, so you'd either have to do this:
*B=*A
or this
B->operator =(*A);
Btw, try to use pointers only when it's necessary - if you are just passing something around, just use references.
edit: Merged the accidental double post
Last edited on Sep 15, 2011 at 10:28am UTC