关于typedef 在类中使用的作用域, 继承以及重载。

1、typedef也是有作用域的,作用域和函数、变量类似。比如类内定义的typedef,要在类外引用就必须在前面加上class_name:: 。并且受到private、public的影响。

2、typedef也具有继承性,比如父类里面定义了typedef,子类里是可以使用的。比如:

class a

{

public:

typedef int typea;

}

class b : public a

{

public:

}

这时候可以使用 a::typea, 也可以使用b::typea, 结果是一样的。


3、typedef同样可以重载,就像函数重载那样。比如:

class c : public a

{

public:

typedef char typea;

}

这种时候typea就被重载了, 这种情况下c类的对象,在调用函数时候c自己的成员函数调用是char、父类a的成员函数调用结果是int.不存在虚继承的情况。


测试代码如下:

class a
{
public:
typedef int typeA;// 4bytes


public:
void testa()
{
printf("class a. typeA size is : %d\n", sizeof(typeA));
}
};
class b : public a
{
public:
void testb()
{
printf("class b. typeA size is : %d\n", sizeof(typeA));
}


};
class c : public a
{
public:
void testc1()
{
printf("class c. before redef. typeA size is : %d\n", sizeof(typeA));
}
typedef char typeA;// 1byte.
void testc2()
{
printf("class c. after redef. typeA size is : %d\n", sizeof(typeA));
}
};
int _tmain(int, _TCHAR*)
{

b objb;

c objc;

printf("Start object with class b test...\n");

objb.testa();

objb.testb();


printf("\nStart object with class c test...\n");

objc.testa();

objc.testc1();

objc.testc2();

printf("\n");

printf("c::typeA size = %d, b::typeA size = %d, a::typeA size = %d\n", sizeof(c::typeA), sizeof(b::typeA), sizeof(a::typeA));


system("pause");

return 0;

}


// 结果:

Start object with class b test...
class a. typeA size is : 4
class b. typeA size is : 4


Start object with class c test...
class a. typeA size is : 4
class c. before redef. typeA size is : 1
class c. after redef. typeA size is : 1


c::typeA size = 1, b::typeA size = 4, a::typeA size = 4
请按任意键继续. . .




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值