您的位置:首页 > 其它

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

2013-03-28 16:05 453 查看
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

请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: