Precautions for C ++ struct Programming

Source: Internet
Author: User

# Include <iostream. h>

Struct structa

{

Int imember;

Char * cmember;

};

 

Int main (INT argc, char * argv [])

{

Structa instant1, instant2;

Char c = 'a ';

Instant1.imember = 1;

Instant1.cmember = & C;

Instant2 = instant1;

Cout <* (instant1.cmember) <Endl;

* (Instant2.cmember) = 'B ';

Cout <* (instant1.cmember) <Endl;

Return 0;

}

Result:

B

The reason is that the instant2 = instant1 value assignment statement uses variable copy one by one, which causes their cmember to point to the same piece of memory.

In C, When pointer members exist in the struct, note that when using the value assignment statementWhether to direct the pointer from the two instances to the same memory address
.

In C ++, when a pointer member exists in the struct, we needOverride the copy constructor of struct and reload the '=' operator.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.