看了c和c++代码精粹 收益颇厚
// 1.0.cpp > #include < stdio.h > class A ... { public : double x; A(double d)//若explicit声明 则显示转化 f(2)改为f(A(2)) ...{ x=d; printf("A::A "); }} ; void f( const A & a) ... { printf("%f ",a.x); } main() ... { A a(1); f(a); f(2); getchar();} // 1.1.CPP 在任意一个转化序列里只允许一个用户定义的转换 #include < stdio.h > struct B; struct A ... { public : double x; A(const B& b); } ; void f( const A & a) ... { printf("%f ",a.x); } struct B ... { double y; B(double d):y(d) ...{ } } ; A::A( const B & b):x(b.y) ... { } int main() ... { A a(1); f(a); B b(2); // f(3); f(B(3)); f(A(4)); getchar(); } Z6
#include < iostream > #include < iomanip > #include < stdlib.h > using namespace std;main() ... { //将日期储存在一个16bit中 //法一 unsigned short date1,date,year=92,mon=8,day=2; date=(year<<9)|(mon<<5)|day; cout<<hex<<date<<endl; //法二 通过位域结构实现 注意为LITTLE ENDIAN struct Date...{ unsigned day:5; unsigned mon:4; unsigned year:7; }; Date *dp=(Date *)&date1; dp->mon=mon; dp->day=day; dp->year=year; cout<<hex<<date1<<endl; getchar();}
// 1.5.CPP 预处理 #include < iostream > #include < iomanip > #include < string > #include < stdlib.h > using namespace std; #if defined(__MSVER) < Put statement here supported by microsoft > #elif defined (__BCPLUSPLUS__) < Put statement here supported by borland > #else main() ... { //RAGGED 数组 char * str[]=...{"now" ,"is","the","time"}; size_t n=sizeof str / sizeof str[0]; for(int i=0;i<n;i++) ...{/**////还如下访问 char *p=str[0];cout<<p; char **p =str;cout<<*(p+i) cout<<"str"<<i<<"=="<<str[i]<<",size="<< sizeof str[i]<<",length="<<strlen(str[i])<<endl; } getchar();}//#error Compiler not supported#endif
// 1.6.CPP 十六进制转ASCII #include < iostream > #include < iomanip > #include < string .h > #include < stdlib.h > #include < stdio.h > using namespace std; long atox_ascii( char * s) ... { long sum; while(isspace(*s)) s++; for(sum=0L;isxdigit(*s);++s) ...{ int digit; if(isdigit(*s)) digit=*s-'0'; else digit=toupper(*s)-'A'+10; sum=sum*16L+digit; } return sum;} long atox_allplatform( char * s) ... { char xdigs[]="0123456789ABCDEF"; long sum; while(isspace(*s)) s++; for(sum=0L;isxdigit(*s);++s) ...{ int digit = strchr(xdigs,toupper(*s))-xdigs; sum=sum*16L+digit; } return sum;} long atox_sscanf( char * s) ... { long n=0L; sscanf(s,"%x",&n); return n; } long atox_great( char * s) ... { return strtol(s,NULL,16); } main() ... { cout<<atox_ascii("2a")<<endl; cout<<atox_allplatform("2a")<<endl; cout<<atox_sscanf("2a")<<endl; cout<<atox_great("2a")<<endl; getchar();}
// 1.7.CPP stdlib qsort #include < iostream > #include < iomanip > #include < string .h > #include < stdlib.h > #include < stdio.h > using namespace std; int comp( const void * p1, const void * p2) ... { const int * p11= (const int *) p1; const int * p21= (const int *) p2; return *p11-*p21;} main() ... { int a[]=...{34,1, 56,23}; qsort(a,sizeof a /sizeof a[0],sizeof a[0],comp); for(int i=0;i<sizeof a /sizeof a[0];i++) cout<<a[i]<<" "; getchar();}
