C ++ efficient programming: Reading Note 1

Source: Internet
Author: User

Mentioned in the last chapter of this bookAlgorithmHere are a few examples of the traps, and write down two.

1. Coverage of cyclic count

If you add 1 to a byte with a value of 255, the byte will change to 0.

UnsignedCharI;
For(I=0;I<256;I++){
Cout<"Test"<(Int)I<Endl;
}

In this case, an infinite loop occurs, because after 255, the value is 0 again.

2. Mixed Array and inheritance

# Include <iostream. h>

ClassAveragejoe
{
Public:
LongID;
};

ClassJetset:PublicAveragejoe
{
Public:
LongVIP;
};

VoidSetid(Averagejoe*Person,LongIndex,LongNumber){
Person[Index].ID=Number;
}

Void Main ( Void ) {
Jetsetvips [ 40 ];
For ( Int I = 0 ; I < 40 ; I ++) {
VIPs [ I ]. VIP = 1 ;
}
Setid ( VIPs , 1 , 0 );
If ( 1 = VIPs [ 0 ]. VIP ) {
Cout < "VIP !!! " < Endl ;
} Else {
Cout < "Not VIP ." < Endl ;
}
// Test
Cout < "Test: \ n" < "VIPS [1]. ID :" < VIPs [ 1 ]. ID < Endl ;
Cout < "VIPS [0]. VIP :" < VIPs [ 0 ]. VIP < Endl ;
}

 

The size of a class averagejoe is 4 bytes, while that of Jetset is 8 bytes. When the setid function is called, the pointer is operated according to the size of averagejoe, and 4 bytes are moved each time.
Solution: Define the setid function as a member function of the base class.

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.