語法
例子 類的通式:
class
class-nameobject-list;
class
vehicle ;
int vehicle::range()
建構函式:
class-name()
class
myclass ;
myclass::myclass()
myclass::~myclass()
拷貝建構函式:
classname(const classname & obj)
在物件作為引數傳遞、由函式返回或用於初始化時,呼叫拷貝建構函式複製物件
只適用於初始化,不適用於賦值
當物件副本不能與原始物件保持一致時呼叫,可以防止原始物件受到破壞
可以訪問類的私有成員,不使用物件和句點運算子
友元函式:
class
myclass;
class
cylinder; // a forward declaration
enum
colors ;
class cube
bool samecolor(cylinder y);
// ...
};
class
cylinder ;
bool cube::samecolor(cylinder y)
結構體:
struct
test // these are public
void put_i(int j) // by default
private:
inti;
};共同體:
union
utype;
運算子過載:
type classname::operator#(arg-list)
threed threed::operator++()
threed threed::operator++(int notused)
//字尾版本的++
class
threed
threed(int i, int j, int k)
threed operator+(threed op2);
void show() ;
}; // overload +.
threed threed::operator+(threed op2)
繼承的通式:
class
derived-class:access bade-class
class
rectangle : public twodshape
類宣告的完整形式:
class
classname;
呼叫基類建構函式:
derived-constructor(arg-list):base-cons(arg-list);
********(char *str, double w,
double h) : twodshape(w, h)
虛函式:
在宣告前加關鍵字virtual
virtual
type func-name(parameter-list)
p->who();
通過基類指標呼叫
class
b
}; class d1 : public b
}; class
d2 : public b
};純虛函式:
virtual
type func-name(parameter-list)=0
virtual
double area()=0;
異常處理:
try...
catch
(type n arg)
catch(...) }}
指定由函式丟擲的異常:
ret-type func-name(arg-list)throw(type-list)
throw;
再次丟擲異常
void
xhandler(int test) throw(int, char, double)
通用函式:
template
ret-type func-name(parameter list)
template
void swapargs(x &a, x &b)
template
void myfunc(type1 x, type2 y)
通用類:
template
class classname
classnameob;
建立類的特定例項
template
class myclass catch (bad_alloc xa)
命名空間:
namespace
using語句:
using
namespace name;
using
name::member;
獲取物件型別typeid:
typeid
(object)
inti, j;
cout << "the type of i is: "
<<
typeid
(i).name();
強制型別轉換:
dynamic_cast
(expr)
inti, j;
cout << "the type of i is: "
<<
typeid
(i).name();
base *bp,b_ob;
derives *dp,d_ob;
bp=&d_ob;
dp=dynamic_cast
(bp);
if(dp) cout<<"cast ok";
C 語法總結
1 const 與volatile 的用法 1 const include include 行引數指向const 型別變數的指標 void display c cons int pi 6 new 與delete 運算子 double pd define pointer variable pd new...
C 語法總結
1 const 與volatile 的用法 1 const include include 行引數指向const 型別變數的指標 void display c cons int pi 6 new 與delete 運算子 double pd define pointer variable pd new...
總結整理 C 基礎語法
輸入輸出 cin n 等同於 scanf d n cout n 等同於 printf d n cout hello world endl 等同於 printf hello world n string類 string s hello world 賦值字串 string s2 s string s3 ...