1多态
class Base2
{
public:
virtual void init()
{
cout << "Base2::init" << endl;
}
Base2()
{
init();
}
};
class Drived :public Base2
{
public:
void init()
{
cout << "Drived::init" << endl;
}
Drived()
{
init();
}
};
int main()
{
Base2 *b = new Drived();
Drived d;
((Base2 *)(&d))->init();
((Base2)d).init();
system("pause");
return 0;
}
输出结果如下:
首先,Drived对象构造期间调用Base2的构造函数,此时virtual函数只能调用的是Base2的函数。
((Base2 *)(&d))->init();相当于用Base2指针指向d对象,能够起到多态的效果。
但是((Base2)d).init();起不到多态的效果。
2位域
struct testx
{
char a : 2;
char b : 2;
char c : 1;//以上3个只要没有超过8位就之占1个字节
int d : 30;
int e : 3;//这两个超过了32位,占8个字节
};
int main()
{
testx t;
cout << sizeof(t) << endl; //输出为9
system("pause");
return 0;
}
typedef struct
{
int a : 2;
int b : 2;
int c : 1;
}test;
main()
{
test t;
t.a = 1;
t.b = 3;
t.c = 1;
cout << t.a << endl;
cout << t.b << endl;
cout << t.c << endl;
}
输出结果是1,-1,-1
解析如下:
因为int是有符号整型,所以它有符号位的,也就是说a和b,实际只能存一个二进制位,另外一个是它的符号位。而c呢,只能表示正负,1就是负,0就是正。
t.a=1相当于使第1位和第0位分别为01
t.b=3相当于使第3位和第2位分别为11
t.c=1相当于使第4位为1
输出结果
t.a,第1位是0所以正数,输出1
t.b,第3位是1所以负数,输出-1
t.c,第4位为1,这就要看编译器怎么处理了,如果把它当成符号位,那就输出-1,如果认为没有符号位,那就输出1
如果想达到输出原数的目的,类型不应使用int而应使用unsigned int,即无符号整型。
3用模板实现是否一个类继承于另一个类
template<typename T, typename TBase>
class TIsDerived
{
public:
static int t(TBase* base)
{
return 1;
}
static char t(void* t2)
{
return 0;
}
enum
{
Result = (sizeof(int) == sizeof(t((T*)NULL))),
};
};
调用:
cout << TIsDerived<Derived2, Base2>::Result;