c++ 函数整理

来源:互联网 发布:英语网络课程 一对一 编辑:程序博客网 时间:2024/05/16 01:51

函数整理

一:内联函数

将函数指定为 inline 函数,(通常)就是将它在程序中每个调用点上“内联地”展开

例:

const string &shorterString(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}

假设我们将 shorterString 定义为内联函数

cout << shorterString(s1, s2) << endl;

在编译时将展开为:

cout << (s1.size() < s2.size() ? s1 : s2)<< endl;

inline const string &shorterString(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}

一般来说,内联机制适用于优化小的、只有几行的而且经常被调用的函数

二:重载函数

void print(const string &);
void print(double); 
void print(int); 
void fooBar2(int ival)
{
print("Value: ");
print(ival); 
print(3.14);
}

三:const 使用

bool Sales_item::same_isbn(const Sales_item &rhs) const
{ return (this->isbn == rhs.isbn); }

bool Sales_item::same_isbn(const Sales_item *const this,const Sales_item &rhs) const
{ return (this->isbn == rhs.isbn); }

total.same_isbn(trans);

const 改变了隐含的 this 形参的类型,在调用total.same_isbn(trans) 时,隐含的 this 形参将是一个指向 total 对象的const Sales_Item* 类型的指针

用这种方式使用 const 的函数称为常量成员函数。由于 this 是指向 const 对象的指针,const 成员函数不能修改调用该函数的对象。因此,函数 same_isbn 只能读取而不能修改调用它们的对象的数据成员。

const 对象、指向 const 对象的指针或引用只能用于调用其const 成员函数,如果尝试用它们来调用非 const 成员函数,则是错误的。

四:构造函数

class Sales_item {
public:
Sales_item(): units_sold(0), revenue(0.0) { }
private:
std::string isbn;
unsigned units_sold;
double revenue;
};

在冒号和花括号之间的代码称为构造函数的初始化列表

五:函数指针

1.函数指针是指指向函数而非指向对象的指针

定义:bool (*pf)(const string &, const string &);

typedef:typedef bool (*cmpFcn)(const string &, const string &);

使用:

假设有函数

bool lengthCompare(const string &, const string &);

cmpFcn pf1 = 0;

pf1 = lengthCompare;

cmpFcn pf2 = lengthCompare;

2.函数指针形参

函数的形参可以是指向函数的指针,这种形参可以用以下两种形式编写

void useBigger(const string &, const string &,bool(const string &, const string &));

void useBigger(const string &, const string &,bool (*)(const string &, const string &));

3.返回指向函数的指针

int (*ff(int))(int*, int);

要理解该声明的含义,首先观察:
ff(int)
将 ff 声明为一个函数,它带有一个 int 型的形参。该函数返回
int (*)(int*, int);
它是一个指向函数的指针,所指向的函数返回 int 型并带有两个分别是int* 型和 int 型的形参。

使用 typedef 可使该定义更简明易懂:

typedef int (*PF)(int*, int);

PF ff(int);

4.指向重载函数的指针

extern void ff(vector<double>);
extern void ff(unsigned int);

指针的类型必须与重载函数的一个版本精确匹配

void (*pf1)(unsigned int) = &ff;







0 0
原创粉丝点击