开发者

How default assignment operator works in struct?

Suppose I have a structure in C++ containing a name and a number, e.g.

struct person {

char name[20];

int ssn;

};

Suppose I declare two person variables:

person a;

person b;

where a.name = "George", a.ssn = 1, and b.name = "Fred" and b.ssn = 2.

Suppose later in the code

a = b;

printf(&quo开发者_JAVA技巧t;%s %d\n",a.name, a.ssn);


The default assignment operator does a member-wise recursive assignment of each member.


The default assignment operator in C++ uses Memberwise Assignment to copy the values. That is it effectively assigns all members to each other. In this case that would cause b to have the same values as a.

For example

a = b;
printf("%s\n", b.name); // Prints: George
b.name[0]='T';
printf("%s\n", a.Name); // Prints George
printf("%s\n", b.name); // Prints Teorge
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜