类的私有成员访问方式:数组
被该类的成员函数访问(类的对象都不能直接访问);函数
友元函数能够访问,在该类中定义友元函数(友元函数也能够访问该类的保护成员)spa
例:class A{friend void func{};}; func函数称为类A的友元函数,可访问类A的私有保护成员;
指针
友元类,例: class A{ friend class B;} ; class B{}; 类B为类A的友元类,可访问A的私有成员。code
new的使用:对象
判断是否分配成功:内存
new失败会抛 bad_alloc异常,除非是nothrow,这个就判断是否为NULLssl
对于throw new,catch bad_alloc异常;对于nothrow new,检查返回的指针是否为NULL;string
new( nothrow )type; //nothrow newclass
待理解:(上述两种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;// 正确