详解C++编程中的sizeof运算符与typeid运算符
sizeof 运算符 sizeof unary-expression sizeof ( type-name ) 备注 #include <iostream> using namespace std; size_t getPtrSize( char *ptr ) { return sizeof( ptr ); } int main() { char szHello[] = "Hello,world!"; cout << "The size of a char is: " << sizeof( char ) << "nThe length of " << szHello << " is: " << sizeof szHello << "nThe size of the pointer is " << getPtrSize( szHello ) << endl; } 示例输出 The size of a char is: 1 The length of Hello,world! is: 14 The size of the pointer is 4 当 sizeof 运算符应用到 class、struct 或 union 类型时,结果为该类型的对象中的字节数,以及添加的用于在字边界上对齐成员数据的任何填充。结果不一定对应于通过将各个成员的存储需求相加计算出的大小。 /Zp 编译器选项和 pack 杂注会影响成员的对齐边界。 typeid 运算符 typeid( type-id ) typeid( expression ) ( expression ) 备注 // expre_typeid_Operator.cpp // compile with: /GR /EHsc #include <iostream> #include <typeinfo.h> class Base { public: virtual void vvfunc() {} }; class Derived : public Base {}; using namespace std; int main() { Derived* pd = new Derived; Base* pb = pd; cout << typeid( pb ).name() << endl; //prints "class Base *" cout << typeid( *pb ).name() << endl; //prints "class Derived" cout << typeid( pd ).name() << endl; //prints "class Derived *" cout << typeid( *pd ).name() << endl; //prints "class Derived" delete pd; } 如果 expression 正在取消引用某个指针,并且该指针的值是零, typeid 将引发 bad_typeid 异常。如果该指针没有指向有效的对象,则会引发 __non_rtti_object 异常来指示尝试了分析引发错误(如访问冲突)的 RTTI,因为该对象在某种程度上是无效的(无效的指针或代码不是用 /GR 编译的)。 // expre_typeid_Operator_2.cpp #include <typeinfo> int main() { typeid(int) == typeid(int&); // evaluates to true } typeid 还可在模板中使用以确定模板参数的类型: // expre_typeid_Operator_3.cpp // compile with: /c #include <typeinfo> template < typename T > T max( T arg1,T arg2 ) { cout << typeid( T ).name() << "s compared." << endl; return ( arg1 > arg2 ? arg1 : arg2 ); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |