C++ Primer Plus读书笔记08

2012-03-09

1、友元类 类(遥控器,Remote)的所有方法可以访问类(TV)的私有,保护成员

class TV

{

     friend class Remote;

}

class Remote

{

……

}//实现

2、友元成员函数 稍复杂,见P543

3、类包含:将类对象作为另一个类的成员

       如class Student{string name;};        //包含string 类成员name

       类嵌套:不创建类成员,只定义类型

4、异常abort()函数    用cstdlib头文件

       作用:向标准错误流cerr发送abnormal program termination

       double func(int x,int y)

{

if(y==0)    

{

    cerr<<”除数不可以为零”<<endl;

    abort();   //发送完abnormal…之后直接终止程序,不返回到main(),相当于exit()

}

}

5、异常机制 throw,try,catch

       int func(int x,int y)

       {

              if(y==0)         throw “除数不可以为0”;

              return x/y;

}

int main()

{

       int x,y,z;

       while(cin>>x>>y)

       {

              try {z=func(x,y);}

              catch(const char *s) {cout<<s<<endl;       continue;}

       }

       cout<<z;

}//异常与处理程序匹配时,执行catch代码块

6、dynamic_cast:类层次中的向上转换

使用条件:Low和High是两个类,ph,pl类型分别是High*,Low*,则仅当Low是High的可访问基类(直接或间接)时,

       pl=static_cast<Low*>ph;才正确

       解释:Low是基类,所以Low的方法High都有,所以将High指针→Low指针

       反过来不行

7、读入方法

       char info[100];     string stuff;

cin>>info;//遇到空格,回车停

cin>>stuff//遇到空格,回车停

cin.getline(info,100)//读一行,丢弃回车

getline(cin,stuff)//读一行,丢弃回车

cin.get(info,100)//读一行,回车留在缓冲区

getline(cin,stuff,’*’)//读一行,遇到*停

cin,getline(info,100,’*’)读一行,遇到*停

 

 

8、ofstream对象的 open方法要求C语言字符串(而非C++的string)

       例: string filename;         cin>>filename;

              ofstream fout;

              fout.open(filename.c_str());

 

2012-03-10

1、智能指针 auto_ptr 防止内存泄漏

 

       引入:void func()

{ string *ps=new string (str);

                     str=ps;

return ;//没加delete ps,则函数结束时指针ps占据的内存被释放,但PS指向的内存没有

           }

∴将指针看做类对象,过期时自动析构

#include<memory>

    auto_ptr<double> p1(new double);

    double *p2=new double;

    *p1=15.1;

    *p2=25.2;      //用法类似,但P1会自动释放,P2必须手动delete

只能对new分配的内存用auto_ptr对象,不能用于new[]分配的

2、STL函数 for _each(),random_shuffle(),sort()

(1)举例:vector<int>test;

vector<int>::iterator pr;

for(pr=test.begin();pr!=test.end();pr++)

    func(*pr);

for_each(test.begin(),test.end(),func);

//等价,其中前两个参数定义区间,最后一个是函数指针

此函数应用于区间中个元素,且不能修改元素的值,作用:避免使用迭代器变量

 

(2)random_shuffle(test.begin(),test.end());随机排列test矢量中的所有元素

(3)random_shuffle(test.begin(),test.end());排序

 

3、算法#include<algothrim>

sort()升序排序

next_pernutation()转换为下一排列方式,如果成功返回true,已处于最后,返回false

 

例:string letter=”wed”;

       sort(letter.begin(),letter.end()); //则letter变为wed,对此题不变

       while(next_pernutation(letter.begin(),letter.end())

                     cout<<letter<<endl;

       则依次输出dew,dwe,edw,ewd,wde,wed //会去掉重复的

posted on 2012-04-06 17:42  TheBest  阅读(313)  评论(0编辑  收藏  举报

导航