@└────> # g++ main.cc -c @└────> # g++ A.cc -c @└────> # nm main.o 0000000000000000 T main U _ZN1A5printEv @└────> # nm A.o U __cxa_atexit U __dso_handle 000000000000006c t _GLOBAL__sub_I__ZN1A5printEv 000000000000002e t _Z41__static_initialization_and_destruction_0ii 0000000000000000 T _ZN1A5printEv U _ZNSolsEi U _ZNSolsEPFRSoS_E U _ZNSt8ios_base4InitC1Ev U _ZNSt8ios_base4InitD1Ev U _ZSt4cout U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ 0000000000000000 r _ZStL19piecewise_construct 0000000000000000 b _ZStL8__ioinit
@└────> # g++ main.cc -c @└────> # g++ A.cc -c @└────> # nm main.o 0000000000000000 T main U _ZN1A5printIiEEvv @└────> # nm A.o U __cxa_atexit U __dso_handle 000000000000003e t _GLOBAL__sub_I_A.cc 0000000000000000 t _Z41__static_initialization_and_destruction_0ii U _ZNSt8ios_base4InitC1Ev U _ZNSt8ios_base4InitD1Ev 0000000000000000 r _ZStL19piecewise_construct 0000000000000000 b _ZStL8__ioinit
#include<iostream> classA { public: int m; template<class T> voidprint(){ std::cout << m << std::endl; } };
编译:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
@└────> # g++ main.cc -c @└────> # nm main.o U __cxa_atexit U __dso_handle 0000000000000059 t _GLOBAL__sub_I_main 0000000000000000 T main 000000000000001b t _Z41__static_initialization_and_destruction_0ii 0000000000000000 W _ZN1A5printIiEEvv U _ZNSolsEi U _ZNSolsEPFRSoS_E U _ZNSt8ios_base4InitC1Ev U _ZNSt8ios_base4InitD1Ev U _ZSt4cout U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ 0000000000000000 r _ZStL19piecewise_construct 0000000000000000 b _ZStL8__ioinit
virtualinttest(){ // 不正确,不能修饰全局函数 // do some thing }
编译报错:
1
error: ‘virtual’ outside class declaration
2. virtual 不能修饰构造函数。
从存储空间角度,虚函数的每个对象内部都有一个指向虚函数表的指针。那么虚函数表是什么时候初始化的呢?就是在调用构造函数的时候。cpp 调用 new 的步骤是,先申请所需的内存(malloc/operator new),再调用构造函数。如果构造函数是虚的,那必须通过虚函数表指针来找到虚构造函数的入口地址。然而此时申请的内存还没有初始化,不可能由虚函数表和虚函数表指针的。综上所述,构造函数不能为虚函数。
double d = 3.14159265; int i = static_cast<int>(d);
如果转换的类型之间没有关系的话,会报编译错误:
1 2 3 4 5
@└────> # g++ test.cc test.cc: In function ‘int main()’: test.cc:12:41: error: invalid static_cast from type ‘Base*’ to type ‘Derived*’ Derived *b = static_cast<Derived *>(a); ^