Essential C++ 之面向过程

来源:互联网 发布:la mer 眼霜 知乎 编辑:程序博客网 时间:2024/06/10 06:37
#include <iostream>using namespace std;bool fibon_elem(int , int &);int main(){    int pos;    cout << "Please entr a position: ";    cin  >> pos;    int elem;    if (fibon_elem (pos,elem))        cout << "element # " << pos             << " is " << elem << endl;    else         cout << "Sorry,Could not calculate element # "             << pos << endl;    return 0; }bool fibon_elem (int pos,int &elem){    //检查位置值合理否    if (pos <= 0 || pos > 1024)    {        cerr << "invalid position: " << pos             << " -- cannot handle request!\n";        return false;    }    //位置值为1和2时,elem的值为1    elem = 1;    int n_2 = 1;    int n_1 = 1;    for ( int ix = 3; ix <= pos; ++ix)    {        elem = n_2 + n_1;        n_2 = n_1;        n_1 = elem;    }return true;}

这种用户想知道的两个或甚至更多元素值,他必须这行这个程序两次
或多次,改写 main( ),使他允许用户不断输入位置值,直到用户希望停止为止

int main(){    int pos;    char ch; //判断是否继续    bool more = true;    while(more)    {        cout << "Please entr a position: ";        cin  >> pos;        int elem;        if (fibon_elem (pos,elem))            cout << "element # " << pos                 << " is " << elem << endl;        else             cout << "Sorry,Could not calculate element # "                 << pos << endl;            cout << "Would you like to try again? (y/n) ";            cin >> ch;            if (ch != 'y' && ch != 'Y')                more = false;     }       return 0; }

Page 67/230
动态内存管理:heap memory
new表达式:

int *p;p = new int ;                   //new Typep = new int ( 1024 ) ;      //new Type ( initial_value)int *pia = new int[24];

heap配置来的对象,都没有经过初始化,而new表达式的另一种表达式允许我们指定初值(见上)
存活期是存活直到delete释放

delete pi;delete [] pi;//删除数组中的所有对象//不使用delete会变成内存泄漏

默认参数值

void bubble_sort (vector<int> &vec,ofstream &ofil ){    //这里的ofil意味着每次调用函数都要传入一个ofstream对象    ……}void bubble_sort (vector<int> &vec,ofstream *ofil = 0){    //这里的将ofstream的指针参数默认值设为0,不使用引用是因为引用无法设为0    //这样子的话,当用户采用单一村塾调用bubble_sort时,不会产生任何调试信息,    //如果调用时带有第二参数,只想某个ofstream对象,你们这个函数就会产生调试信息    ……}
//在display中使用默认参数,让cout成为默认ostream参数void display( const vector<int> &vec, ostream &os = cout ){    for (int ix = 0;ix < vec.size(); ++ix)        os << vec[ix] << ' ';    os << endl;}

为了更高的可见度,默认值置于函数声明处,而非定义处,因此,display( )的
声明和定义通常是:
//头文件声明,其中指定了参数默认值
//让我们称此头文件为:NumericSeq.h
void display (const vector<int>& , ostream&=cout);
//程序本文含入上诉头文件
//置于函数定义处,并没有指定参数的默认值
#include "NumericSwq.h"
void display (const vector<int> &vec,ostream &os)
{
for (int ix = 0;ix < vec.size(); ++ix)
os << vec[ix] << ' ';
os << endl;
}

(page 71/230) 使用局部静态对象

const vector<int>*fibon_seq(int size){    static vector< int > elema; //处于全局静态区,每次调用不会被破坏}

了解
inline:
重载函数:
模板函数:将参数表中指定的所有(或部分)参数的型别信息抽离出来,
这份信息由用户提供,当他决定用function template的某个实体时提供

//以关键词template开场,其后<>包围起来一个或多个识别名称,
//这些名称用来表示我们希望【延缓决定的数据类型】
template <typename elemType>
void display_message( const string &msg,
const vector <elemType> &vec )
{
cout << msg;
for (int ix = 0; ix <vec.size(); ++ix )
{
elemType t = vec[ ix ];
cout << t << ' ';
}
}
//elemType只是一个代称,可以是任意名称
一般而言,如果函数具备多种实现方式,我们可以将它重载,
如果仅仅改变其中用到的数据型别,可以通过function template

//function template 再经重载 overloadedtemplate <typename elemType>void display_message(const string &msg,const vector<elemType> &vec );template <typename elemType>void display_message(const string &msg,const list<elemType> &lt); 

函数指针带来更大弹性
当我们提供“类似于返回fabonacci数列中指定位置的数字,通过vector返回另外几种
数列”的函数,做法之一是分别定义函数:

const vector<int> *fibon_seq(int size);const vector<int> *lucas_seq(int size);//……

但是对于fibon_elem( )这种,我们不应该针对六个数列提供六种函数

bool fibon_elem (int pos,int &elem){    const vector<int> *pseq = fibon_seq(pos);//仅此与数列有关(A)    if (! pseq)        { elem = 0; return false;}    elem = (*pseq)[ pos - 1];    return true;}

我们消除这个(A),就可以消除这个关联性,就不必提供多个fibon_elem( ) 相似函数了。 使用函数指针,返回类型为const vector<int>* ,参数表内容为 int,定义的是一个指针,需要一个名称,姑且称为seq_ptr。
const vector<int>* (*seq_ptr)( int ); //最终形式
此时,seq_ptr指向“具有所列之返回值类型以及参数表”的任何一个函数。

//现在将fibon_elem()重新写过,使其为更加通用的seq_elem()bool seq_elem (int pos,int &elem,                const vector<int>* (*seq_ptr)(int)){    //调用seq_ptr所指函数    const vector<int> *pseq = seq_ptr(pos);    if (!pseq)    {        elem = 0;        return fasle;    }    elem = (*pseq)[pos-1];    return true;}
//也可以使用数组来存放函数指针const vector<int>* (*seq_array[])(int) = {        fibon_seq,lucas_seq,pell_seq,        tring_seq,square_seq,pent_seq};//可以使用辅助记忆的常量来索引操作,就不需要记住对应函数是哪一个下标了enum ns_type {     ns_fibon, ns_lucas, ns_pell,     ns_triang, ns_square, ns_pent};seq_ptr = seq_array[ ns_pell ];

一次定义规则下的例外情况
inline:
const object:此定义一出文件之外就不可见,其他的需要用extern声明

0 0
原创粉丝点击