c++程序员修炼真经
第一章 闲话基础
这些年项目做了一大堆,感慨C/C++程序员生存之悲凉,特写下这部手册供大家参考,我不是专家也不是权威,错误之处
大家不要骂我,我只是为了让年轻的程序员有更多解决问题的方法.
一:基础知识
写程序先从小的地方做起不起眼的脚落往往容易出错
1.请务必记住在不同的C++实现中,非char类型未必具有同样的大小,空类和空结构的大小不是0而是1
测试程序:
#include <iostream>
using namespace std;
struct nnv
{
};
struct nnu
{
bool check_active(){return true;}
};
class Nk
{
public:
virtual void add(int& x){x++;}
protected:
private:
};
class AA{
int x;
public:
AA(int xx=0) : x(xx){}
virtual void print(){cout<<"x="<<x<<endl;}
};
class BB : public AA{
int y;
public:
BB(int xx=0, int yy=0) : AA(xx){y=yy;}
virtual void print()
{
AA::print();
cout<<"y="<<y<<endl;
}
};
class CC : public AA{
int z;
public:
CC(int xx=0, int zz=0) : AA(xx){z=zz;}
virtual void print()
{
AA::print();
cout<<"z="<<z<<endl;
}
};
class DD:public AA,public Nk
{
public:
int id;
DD(int xx=0,int prmid=0):AA(xx){id=prmid;}
virtual void print()
{
AA::print();
cout<<"id="<<id<<endl;
}
virtual void add(int& x)
{
x+=id;
cout<<x<<endl;
}
protected:
private:
};
class EE
{
public:
void fun1(int & x){x++;}
bool isEmpty(){return false;}
protected:
private:
};
void main()
{
AA a(2);
BB b(3,4);
CC c(5,6);
Nk tm;
DD d(7,8);
EE e;
struct nnv strucX;
struct nnu strucY;
int acount,bcount,ccount;
acount=sizeof(a);
bcount=sizeof(b);
ccount=sizeof(c);
int i9=sizeof(tm);
int i7=sizeof(strucY);
int i5=sizeof(d);
int i1=sizeof(e);
AA *p[3]={&a,&b,&c};
for(int i=0; i<3; i++)
p[i]->print();
system("pause");
}
2.宏替换,各种陷阱从此开始
#define N 3
#define Y(n) ((N+1)*n)
int ny=Y(5+1);
大家可以测一下,ny等于多少
二.来点更常用的的:
1.写一个itoa
template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
{
if (base < 2 || base > 16)
{
*res = 0;
return res;
}
char* out = res;
int quotient = in;
while (quotient)
{
*out = "0123456789abcdef"[ std::abs( quotient % base ) ];
++out;
quotient /= base;
}
if(in <0&&base==10)
*out++ = '-';
std::reverse( res, out );
*out = 0;
return res;
}
2.实现一个配置文件解析
map<string, string> gmapConfInof;
void Open( const char *szFile)
{
gmapConfInof.clear( );
ifstream in;
in.open( szFile );
if( in.fail( ) )
{
return;
}
while( !in.eof( ) )
{
char pBuf[1024];
in.getline( pBuf, 1023 );
string strTemp = pBuf;
// 忽略空行和注释
if( strTemp.empty( ) || strTemp[0] == '#' )
continue;
string :: size_type iSplit = strTemp.find( "=" );
if( iSplit == string :: npos )
continue;
string :: size_type iKeyStart = strTemp.find_first_not_of( " " );
string :: size_type iKeyEnd = strTemp.find( " ", iKeyStart );
string :: size_type iValueStart = strTemp.find_first_not_of( " ", iSplit + 1 );
string :: size_type iValueEnd = strTemp.size( );
if( iValueStart != string :: npos )
gmapConfInof[strTemp.substr(iKeyStart,iKeyEnd-iKeyStart)] = strTemp.substr
(iValueStart, iValueEnd - iValueStart);
}
in.close( );
}
结束语:
后续章节我会和大家探讨一些具体的项目问题涉及到ATL,WTL,BHO,ACE,STL,Boost,XML,XMPP等等
本文为C/C++程序员提供了一份实用的手册,旨在帮助解决实际编程中遇到的问题。文中通过实例讲解了C++中易犯的错误,如不同类型的大小差异、空类的大小等,并分享了一个通用的itoa函数模板及配置文件解析方法。
1127

被折叠的 条评论
为什么被折叠?



