1. 對象的空間在括号開始就已經配置設定,但是構造在定義對象的時候才會實作,若跳過(譬如goto),到括号結束析構會發生錯誤,編譯會通不過。
2.初始化
1 struct X { int i ; float f; char c;};
2
3 - X x1 = { 1,2.2,'c'};
4 X x2[3] = { {1,1.1,'a'},{2,2.2,'b'} };
5
6
7 struct Y {float f; int i; Y(int a);} ;
8
9 Y y1[] = {Y(1),Y(2),Y(3)};
3. default constructor == 無參數構造函數
Y y2[2] = {Y(4);} //it is wrong
4. new / delete
new : 配置設定空間+調用構造函數
delete(delete[]): 先析構,後回收空間
int *psome = new int [10];
delete [] psome; //不能失去[]
不要用delete去free不是new的空間
不要對同一個記憶體空間delete兩次
當用new[]時,必須用delete[]
new不帶[],delete也不帶
對一個空指針delete是安全的(nothing will happen):不确定是否用new時使用
沒delete。記憶體洩漏。
int *p = new int;
int *a = new int[10];
Student *q = new Student();
Student *r = new Student[10];
delete p; //p的位址與大小
a++;delete[] a; //運作錯誤,找不到new時a的位址
delete q; //回收Student
delete r; //空間收回,析構隻做了一個
delete[] r; //析構所有對象
僅在編譯時刻
--public:公用的
--private:自己--類的成員函數,同類的兩個對象可以互相通路私有變量。
--protected:
Friend: 别的類,别的類裡面的函數。
struct X; //前項聲明
struct Y{
void f(X*);
};
struct X{
private:
int i;
public:
void initialize();
friend void g(X*,int); //Global friend
friend void Y::f(X*); //Struct member friend
friend void Z; //Entire struct is a friend
friend void h();
};
class vs. struct
class 預設的是private
struct 預設的是public
首選class
struct A{
private:
int i;
public:
A:i(0){}
} //與放在裡面相比,實作指派的順序會早于構造函數被執行
盡量用初始化不用指派
轉載于:https://www.cnblogs.com/jinjin-2018/p/9343955.html