如何判斷一段程序是由C 編譯程序還是由C++編譯程序編譯的?
答案:
- #ifdef __cplusplus
- cout<<"c++";
- #else
- cout<<"c";
- #endif
如何打印出當(dāng)前源文件的文件名以及源文件的當(dāng)前行號?
答案:
cout << __FILE__ ;
cout<<__LINE__ ;
__FILE__和__LINE__是系統(tǒng)預(yù)定義宏,這種宏并不是在某個文件中定義的,而是由編譯器定義的。
main 主函數(shù)執(zhí)行完畢后,是否可能會再執(zhí)行一段代碼,給出說明?
答案:可以,可以用_onexit 注冊一個函數(shù),它會在main 之后執(zhí)行。
- #include <iostream>
- using namespace std;
-
- int fn1()
- {
- printf( "next.\n" );
- return 0;
- }
- int fn2()
- {
- printf( "executed " );
- return 0;
- }
- int fn3()
- {
- printf( "is " );
- return 0;
- }
- int fn4()
- {
- printf( "This " );
- return 0;
- }
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- _onexit( fn1 );
- _onexit( fn2 );
- _onexit( fn3 );
- _onexit( fn4 );
- printf( "This is executed first.\n" );
-
- return 0;
- }
輸出結(jié)果為:

The _onexit function is passed the address of a function (func) to be called when the program terminates normally. Successive calls to _onexit create a register of functions that are executed in LIFO (last-in-first-out) order. The functions passed to _onexit cannot take parameters.
類成員函數(shù)的重載、覆蓋和隱藏區(qū)別?
答案:
a.成員函數(shù)被重載的特征:
(1)相同的范圍(在同一個類中);
(2)函數(shù)名字相同;
(3)參數(shù)不同;
(4)virtual 關(guān)鍵字可有可無。
(5)const的區(qū)別
b.覆蓋是指派生類函數(shù)覆蓋基類函數(shù),特征是:
(1)不同的范圍(分別位于派生類與基類);
(2)函數(shù)名字相同;
(3)參數(shù)相同;
(4)基類函數(shù)必須有virtual 關(guān)鍵字。
c.“隱藏”是指派生類的函數(shù)屏蔽了與其同名的基類函數(shù),規(guī)則如下:
(1)如果派生類的函數(shù)與基類的函數(shù)同名,但是參數(shù)不同。此時,不論有無virtual關(guān)鍵字,基類的函數(shù)將被隱藏(注意別與重載混淆)。
(2)如果派生類的函數(shù)與基類的函數(shù)同名,并且參數(shù)也相同,但是基類函數(shù)沒有virtual 關(guān)鍵字。此時,基類的函數(shù)被隱藏(注意別與覆蓋混淆)