C++ storage allocation + Dynamic memory allocation + setting limits + initializer list (1)

1. 對象的空間在括號開始就已經分配,可是構造在定義對象的時候纔會實現,若跳過(譬如goto),到括號結束析構會發生錯誤,編譯會通不過。安全

2.初始化app

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 spa

new :  分配空間+調用構造函數指針

delete(delete[]): 先析構,後回收空間code

int *psome = new int [10];

delete [] psome;     //不能失去[]

不要用delete去free不是new的空間對象

不要對同一個內存空間delete兩次blog

當用new[]時,必須用delete[]內存

new不帶[],delete也不帶it

對一個空指針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){}

}  //與放在裏面相比,實現賦值的順序會早於構造函數被執行

儘可能用初始化不用賦值

相關文章
相關標籤/搜索