类的私有成员访问方式:
被该类的成员函数访问(类的对象都不能直接访问);
友元函数可以访问,在该类中定义友元函数(友元函数也可以访问该类的保护成员)
例:class A{friend void func{};}; func函数称为类A的友元函数,可访问类A的私有保护成员;
友元类,例: class A{ friend class B;} ; class B{}; 类B为类A的友元类,可访问A的私有成员。
new的使用:
判断是否分配成功:
new失败会抛 bad_alloc异常,除非是nothrow,这个就判断是否为NULL
对于throw new,catch bad_alloc异常;对于nothrow new,检查返回的指针是否为NULL;
new( nothrow )type; //nothrow new
待理解:(上述两种new都可以通过set_new_handler在bad_alloc被抛出或者nothrow new返回NULL前对分配失败的情况进行处理。)
为什么用new不用malloc? 用new的时候会发生两件事,首先,内存被分配,然后,为被分配的内存调用一个或多个构造函数,而malloc只会分配内存。
Delete的使用:
有两种使用形式,delete p,delete []p,第一种是删除一个对象,第二种是删除多个对象,必须对应之前new的操作。
例:(来源:Effective C++)
string *stringptr1 = new string;
string *stringptr2 = new string[100];
...
delete stringptr1;// 删除一个对象
delete [] stringptr2;// 删除对象数组
typedef string addresslines[4]; //一个人的地址,共4行,每行一个string
//因为addresslines是个数组,使用new:
string *pal = new addresslines; // 注意"new addresslines"返回string*, 和
// "new string[4]"返回的一样
delete时必须以数组形式与之对应:
delete pal;// 错误!
delete [] pal;// 正确