* sizeof
三种形式
sizeof(type name); //注:没有sizeof typename 所以sizeof int 错误, 只能sizeof(int);
sizeof(object); //sizeof(i_rec);
sizeof object; //sizeof i_rec;
当object为数组时,返回整个数组的长度,并不是元素的个数
int ia[] = {2, 3, 4};
int size = sizeof(ia); //返回4*3 = 12
当object为指针时,返回指针本身占用的内存空间
zeof(short *); //返回4, 指针本身的占用空间
当object为引用时,返回引用所指对象的空间
sizeof(short &) //返回2
*逗号操作符
int a=0, b,c ;
int xx = (1==1)
? (a=8, b=7)
: (b=3, c=2);
结果为最右边表达式结果的值,上面xx = 7
*位操作
构造一个比特位组可以用整形数位移的方法得到。例如:1<<27 是将第27位设置为1
设置某位值为1的方法:
unsigned int quizl = 1;
quizl |= 1<<27; //1<<27构造出第27位为1,其它位为0, quizl与之或, 第27位被置为1, 其它位不变。
设置某位值为0的方法:
quizl &= ~(1<<27) //~(1<<27)构造出第27位为0, 其它位为1, quizl与之与,第27位被置为0, 其它位不变。
判断某位是否为0、1的方法:
bool hasPassed = quizl & (1<<27); //1<<27构造出第27位为1,其它位为0,quizl与之与,除27位外都被置为0,如果quizl的第27位也为0,
则quizl & (1<<27); 的结果也为0, 否则为非0,便可判断第27位是否为1
下面是一个bit位操作的例子:
class bitset
{
public:
bool bit_on(unsigned int ui, int pos);
bool bit_off(unsigned int ui, int pos);
void bit_turn_on(unsigned int &ui, int pos);
void bit_turn_off(unsigned int &ui, int pos);
};
inline bool bitset::bit_on(unsigned int ui, int pos)
{
return ui & (1<<27);
}
inline bool bitset::bit_off(unsigned int ui, int pos)
{
return !bit_on(ui, pos);
}
inline void bitset::bit_turn_on(unsigned int &ui, int pos)
{
ui |= (1<<pos);
}
inline void bitset::bit_turn_off(unsigned int &ui, int pos)
{
ui &= ~(1<<pos);
}
另外,从泛型编程的角度考虑,代码可改写如下:
template <class Type>
class bitset
{
public:
bool bit_on(Type ui, int pos);
bool bit_off(Type ui, int pos);
void bit_turn_on(Type &ui, int pos);
void bit_turn_off(Type &ui, int pos);
};
template <class Type>
inline bool bitset<Type>::bit_on(Type ui, int pos)
{
return ui & (1<<pos);
}
template <class Type>
inline bool bitset<Type>::bit_off(Type ui, int pos)
{
return !bit_on(ui, pos);
}
template <class Type>
inline void bitset<Type>::bit_turn_on(Type &ui, int pos)
{
ui |= (1<<pos);
}
template <class Type>
inline void bitset<Type>::bit_turn_off(Type &ui, int pos)
{
ui &= ~(1<<pos);
}
使用示例1:
unsigned char quizl = 0;
bitset<unsigned char> bit;
bit.bit_turn_on(quizl, 5);
//bit.bit_turn_off(quizl, 5);
cout << bit.bit_on(quizl, 5) <<endl;
使用示例2:
unsigned int quizl = 0;
bitset<unsigned int> bit;
bit.bit_turn_on(quizl, 5);
//bit.bit_turn_off(quizl, 5);
cout << bit.bit_on(quizl, 5) <<endl;