简体   繁体   中英

Compiler error at use of assignment operator to copy an array in two classes

I'm overloading assignment operator function to copy a char array to another char array in different objects. I can call the overloaded assignment operator function but not using assignment.

Can you please give me some guidance what I'm doing wrong? Can I use two classes using the assignment operator?

Thank you, Sergio

pTest = myData;//Fails

pTest->operator=(myData);//this works
struct Data {
char sourceName[5] = { 'S','o','l' };
};

class Test {
public:
//virtual void operator=(Data data) = 0;
void operator=(Data data);
void Show();
private:
char nameTest1[10];
};

void Test::operator=(Data data) {
strcpy_s(nameTest1, data.sourceName);
}

void Test::Show() {
cout << nameTest1;
}

int main() {
Test *pTest = new Test();
Data myData;
pTest = myData;//Fails
pTest->operator=(myData);//but this works
}

Expected result: array sourceName from data object is assigned to array nameTest1 in object Test.

pTest is a pointer.

*pTest = myData;

should work.

Try and keep in mind that a pointer and what it points to are two different things. Both can be manipulated in C++ code, and so newbies often get them mixed up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM