C++ 程式簡介

第一個程式

#include <iostream.h>   // preprocessing directive

/* traditional first program
   author: S.Y. Lee, 9/17/96 */

int main()      // main program
{               // body
    cout << "Hello world" << endl;   // output statement
    return 0;                        // return statement
}

說明

  1. 主程式
  2. 敘述 (statement)
  3. #include <iostream.h>
  4. 單列的註解, 用 // 起頭; 多列的註解, 用一對 /* 和 */ 括起來。

樣板

// main program template

#include 

int main()
{
   statements
}

敘述

輸出(output)敘述

        cout << ExprOrString << ExprOrString ...; 

輸入(input)敘述

        cin >> name;

指定(assignment)敘述

	v = exp;

v 為變數, 而 exp 為陳式(expression)。 陳式是由運算元(operand)和運算子(operator)組成。 運算元可以是變數或常數。 變數在使用前,必須先宣告其資料型式。

C++ 提供的基本資料型式 (Data types)有

字元值
        char            unsigned char           signed char

例如: char Letter = 'A'; 整數值

        short int       unsigned short int      signed short int
        int             unsigned int            signed int
        long int        unsigned long int       signed long int

例如: int i = 3; 實數值

        float
        double
        long double

例如: float Rate = 0.125;

類型強制(Coercion)

        int i;
        float x;
        i = 4.8;
        x = i + 4.8;

類型轉換(Casting)

        i = int(4.8);
        x = float(i + 9) + 5.7;

算術運算子

運算 運算子 例子
  + i + 9
  - a - c
  * a * b
  / x / y
整數除   % r % s

Precedence Rules

        ()
        * / %
        + -

複合(Compound) 敘述

幾個敘述可用一對 { } 括起來,當做一個敘述使用。 例如:
  if (g > 60) {
    cout << "Passed"; Passed="1;" }

程式例子

#include <iostream.h>

int main(void)
{
   cout << "\nThis program converts a temperature\n"
        << "\tfrom Fahrenheit to Celsius.\n";

   double FahrenheitTemp;
   cout << "\nPlease enter a Fahrenheit temperature: ";
   cin>> FahrenheitTemp;

   double
      CelsiusTemp = (FahrenheitTemp - 32.0) / 1.8;

   cout << "\n\t" << FahrenheitTemp << " in Fahrenheit is equivalent to "
        << CelsiusTemp << " in Celsius.\n\n";
   return 0;
}

Namespaces

假如所用的 compiler, 符合 ANSI/ISO draft standard:
#include <iostream>   // preprocessing directive

using namespace std;

int main()     // main program
{              // body
    cout << "Hello world" << endl;  // output statement
    return 0;                       // return statement
}

Program Editing, Compiling and Running

Editing

>edit xmp1.cc

Compiling

>gcc -c xmp1.cc

>gxx xmp1.cc -o xmp1

Running

>xmp1