恐怖的C++之--class name的作用域和sizeof

本文探讨了C++中名称解析的规则,特别是当类名与变量名发生冲突时如何正确引用类。同时介绍了使用sizeof操作符的正确方式以避免编译错误。

9.1 Class names

2. A class definition introduces the class name into the scope where it is defined and hides any class, object,function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in ascope where an object, function, or enumerator of the same name is also declared, then when both declarationsare in scope, the class can be referred to only using an elaborated-type-specifier (3.4.4).

 

ContractedBlock.gifExpandedBlockStart.gif代码
struct aa{int k[20];};
void *bb = NULL;
int main(){
void *aa = NULL;
struct bb{int k[20];};
struct cc{int k[20];};
void *cc = NULL;
void *dd = NULL;
struct dd{int k[20];};
printf(
"%u %u %u %u",sizeof(aa),sizeof(bb),sizeof(cc),sizeof(dd));
return 1;
}

所以这段代码的输出能够确定为4 80 4 4

 

如果想避免混淆,也可以这样做

如果需要T是个type的话,sizeof(const T)

如果需要V是个变量,或者表达式的话,sizeof((V));

这样编译器会做检查。

 

总结,C++真的很蛋疼。

转载于:https://www.cnblogs.com/aoaoblogs/archive/2010/08/23/1806724.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值