鍙橀噺鍚嶇粰鎴戜滑鎻愪緵浜嗗湪紼嬪簭涓垜浠彲浠ヤ嬌鐢ㄧ殑絀洪棿淇℃伅銆傛瘡涓彉閲忓湪 C++ 涓兘鏈変竴涓壒瀹氱殑綾誨瀷錛屽畠鍐沖畾鍙橀噺鍦ㄥ唴瀛樹腑鐨勫ぇ灝忓拰甯冨眬錛涘湪璇ュ唴瀛樼┖闂村彲浠ュ瓨鏀懼彇鍊艱寖鍥達(dá)紱鍜屼竴緇勫彲浠ュ簲鐢ㄤ簬璇ュ彉閲忕殑鎿嶄綔銆?/p>
涓€涓彉閲忕殑鍚嶇О鍙互鐢卞瓧姣嶃€佹暟瀛楀拰涓嬪垝綰垮瓧絎︾粍鎴愩€傚畠蹇呴』浠ュ瓧姣嶆垨涓嬪垝綰垮紑濮嬨€傚ぇ鍐欏拰灝忓啓鐨勫瓧姣嶆槸涓嶅悓錛屽洜涓?C++ 鏄尯鍒嗗ぇ灝忓啓鐨?
C++ 涓湁浠ヤ笅鍩烘湰鍙橀噺綾誨瀷錛屾垜浠湪涓婁竴鑺傚凡緇忎粙緇嶈繃:
綾誨瀷 | 鎻忚堪 |
---|---|
bool | 瀛樺偍鐨勫€間負(fù) true 鎴栬€?false |
char | 閫氬父鏄?8 浣?涓€浣嶅瓧鑺?銆傚畠鏄釜鏁存暟綾誨瀷銆?/td> |
int | 鏈哄櫒涓渶甯哥敤鐨勬暣鏁扮被鍨嬨€?/td> |
float | 鍗曠簿搴︽誕鐐圭被鍨嬬殑鍊箋€?/td> |
double | 鍙岀簿搴︽誕鐐圭被鍨嬬殑鍊箋€?/td> |
void | 浠h〃鐫€緙哄け綾誨瀷銆?/td> |
wchar_t | 涓€涓瀛楃綾誨瀷銆?/td> |
C++ 榪樺厑璁稿畾涔夊悇縐嶅叾浠栫被鍨嬬殑鍙橀噺錛屾垜浠皢鍦ㄥ悗緇珷鑺傚皢浼?xì)浠嬀l嶇殑錛屾瘮濡?Enumeration錛屾寚閽堬紝鏁扮粍錛屽紩鐢紝鏁版嵁緇撴瀯鍜岀被銆?/p>
涓嬩竴鑺傚皢浠嬬粛濡備綍瀹氫箟錛屽0鏄庡拰浣跨敤鍚勭綾誨瀷鐨勫彉閲忋€?/p>
涓€涓彉閲忓畾涔夋剰鍛崇潃鍛婅瘔緙栬瘧鍣紝瀛樺偍鍦ㄥ摢閲屼互鍙?qiáng)闇€瑕佸灝戠殑瀛樺偍絀洪棿銆傚彉閲忓畾涔夎鎸囧畾鏁版嵁綾誨瀷錛屽悓鏃跺寘鍚綾誨瀷鐨勪竴涓垨澶氫釜鍙橀噺鐨勫垪琛細(xì)
type variable_list;
鍦ㄨ繖閲岋紝type 蹇呴』鏄竴涓湁鏁堢殑 C++ 鏁版嵁綾誨瀷錛屽寘鎷?char錛寃_char錛宨nt錛宖loat錛宒ouble錛宐ool 鎴栬€呬換浣曠敤鎴瘋嚜瀹氫箟鐨勫璞$瓑銆?strong>variable_list 瑕佸寘鍚竴涓垨澶氫釜鐢遍€楀彿鍒嗛殧鐨勬爣璇嗙銆傚涓嬫槸涓€浜涙湁鏁堢殑澹版槑紺轟緥錛?/p>
int i, j, k;
char c, ch;
float f, salary;
double d;
int i,j,k; 榪欎竴琛屽悓鏃跺0鏄庡拰瀹氫箟浜嗗彉閲?i錛宩 鍜?k錛岃繖鏉¤鍙ユ寚紺虹紪璇戝櫒鍒涘緩綾誨瀷涓?int錛屽悕縐頒負(fù) i錛宩 鍜?k 鐨勫彉閲忋€?/p>
鍙橀噺鍦ㄥ0鏄庣殑鍚屾椂鍙互榪涜鍒濆鍖?鍒嗛厤涓€涓垵濮嬪€?銆傚垵濮嬪寲鐢變竴涓瓑鍙峰悗闈㈣窡鐫€涓€涓父鏁拌〃杈懼紡濡備笅:
type variable_name = value;
濡備笅鏄竴浜涚ず渚嬶細(xì)
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
娌℃湁鍒濆鍖栫殑瀹氫箟錛氶潤鎬佺被鍨嬬殑鍙橀噺浼?xì)闅愬紡鍦拌鍒濆鍖栦?NULL(鎵€鏈変綅鍊間負(fù)0)錛岃€屽叾浠栫殑鎵€鏈夊彉閲忕殑鍒濆鍊兼槸鏈煡鐨勩€?/p>
鍙橀噺澹版槑涓虹紪璇戝櫒鎻愪緵淇濊瘉錛屽浜庣粰瀹氱殑綾誨瀷鍜屽悕縐扮殑鍙橀噺鏄敮涓€鐨勶紝浠庤€岀紪璇戝櫒鍦ㄨ繘涓€姝ヨ繘琛岀紪璇戝彉閲忔椂涓嶉渶瑕佸彉閲忕殑瀹屾暣緇嗚妭銆傚彉閲忓0鏄庡彧鏄湪緙栬瘧鏃舵湁鎰忎箟鐨勶紝鍥犱負(fù)緙栬瘧鍣ㄥ湪榪涜紼嬪簭鐨勯摼鎺ユ椂闇€瑕佸彉閲忓0鏄庣殑淇℃伅銆?/p>
褰撲綘浣跨敤澶氫釜鏂囦歡錛屽茍涓斾綘鑷繁瀹氫箟鐨勫彉閲忔斁鍦ㄥ叾涓竴涓枃浠墮噷錛屽彉閲忕殑澹版槑灝嗗紼嬪簭鐨勯摼鎺ュ緢鏈夌敤銆傛?zhèn)ㄥ彲浠ヤ娇鐢?extern 鍏抽敭瀛楁潵澹版槑涓€涓斁鍦ㄤ換浣曚綅緗殑鍙橀噺銆傝櫧鐒朵綘鍦ㄤ綘鐨?C++ 紼嬪簭涓綘鍙互澹版槑涓€涓彉閲忓嬈★紝浣嗗畠鍦ㄤ竴涓枃浠朵腑錛屼竴涓嚱鏁版垨涓€鍧椾唬鐮佷腑鍙兘瀹氫箟涓€嬈°€?/p>
璇曡瘯涓嬮潰鐨勪緥瀛愶紝涓€涓彉閲忓凡緇忓湪欏墮儴榪涜浜嗗0鏄庯紝浣嗗悓鏃跺畠涔熷湪 main 鍑芥暟涓瀹氫箟浜?
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
涓婇潰鐨勪唬鐮佺紪璇戝拰鎵ц鍚庯紝瀹冧駭鐢熶互涓嬬粨鏋?
30
23.3333
鐩稿悓鐨勬蹇典篃鍙互搴旂敤浜庡嚱鏁板0鏄庯紝褰撲綘瀵逛竴涓嚱鏁拌繘琛屽0鏄庢椂錛屽畠鐨勫畾涔夊彲浠ュ湪鍏朵粬浠諱綍鍦版柟銆備緥濡?
// function declaration
int func();
int main()
{
// function call
int i = func();
}
// function definition
int func()
{
return 0;
}
C++ 涓湁涓ょ琛ㄨ揪寮忥細(xì)
鍙橀噺鏄乏鍊?鍥犳鍙兘浼?xì)鍑虹幇鍦ㄨ祴鍊艱鍙ョ殑宸﹁竟銆傛暟瀛楀瓧闈㈠€兼槸鍙沖€鹼紝鍥犳涓嶈兘琚祴鍊鹼紝涓嶈兘鍑虹幇璧嬪€艱鍙ョ殑鍦ㄥ乏杈廣€備笅闈㈡槸涓€涓湁鏁堢殑璇彞:
int g = 20;
浣嗗涓嬪嵈涓嶆槸涓€涓湁鏁堢殑璧嬪€艱鍙ワ紝浼?xì)漶旂敓缂栬瘧鏈熼敊璇?
10 = 20錛?/code>