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

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时使用

扫描二维码关注公众号,回复: 2274420 查看本文章

没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){}

}  //与放在里面相比,实现赋值的顺序会早于构造函数被执行

尽量用初始化不用赋值

猜你喜欢

转载自www.cnblogs.com/jinjin-2018/p/9343955.html