1.string类
虽然string类和c-风格字符串类似,但与数组相比,string与结构更相似,例如可以把一个结构赋给另一个结构,也可以把一个string类赋给另一个string类,可以将结构作为完整的实体传递给函数,也可以将对象作为完整的实体进行传递,如果需要多个字符串,可以声明一个string数组,而不是二维数组。
2.C++中的for循环新用法
int my_array[5] = {1, 2, 3, 4, 5};
// 每个数组元素乘于 2
for (int &x : my_array)
{
x *= 2;
cout << x << endl;
}
// auto 类型也是 C++11 新标准中的,用来自动获取变量的类型
for (auto &x : my_array) {
x *= 2;
cout << x << endl;
}
上面for述句的第一部分定义被用来做范围迭代的变量,就像被声明在一般for循环的变量一样,其作用域仅只于循环的范围。而在”:”之后的第二区块,代表将被迭代的范围。
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main()
{
string str("some string");
// range for 语句
for(auto &c : str)
{
c = toupper(c);
}
cout << str << endl;
return 0;
}
上面的程序使用Range for语句遍历一个字符串,并将所有字符全部变为大写,然后输出结果。
3.函数与array对象
在C++中,类对象是基于结构的,因此结构编程方面的有些考虑因素也适用于类,例如可以直接将对象传递给函数,在这种情况下,函数处理的是原始对象的副本,另外,也可传递指向对象的指针,这让函数能够操作原始对象。
**注:模板array并非只能存储基本数据类型,它还可存储类对象。
#include <iostream>
#include <array>
#include <string>
using namespace std;
const int Seasons=4;
const array<string,Seasons>Snames=
{"Spring","Summer","Fail","Winter"};
void fill(array<double,Seasons>*pa);
void show(array<double,Seasons>da);
int main()
{
array<double,Seasons>expenses;
fill(&expenses);
show(expenses);
return 0;
}
void fill(array<double,Seasons>*pa)
{
for(int i=0;i<Seasons;i++)
{
cout<<"Enter "<<Snames[i]<<"expenses: ";
cin>>(*pa)[i];
}
}
上述代码将array对象传入函数,来进行处理。
4.函数指针
与数据项类似,函数也有地址,函数的地址是存储其机器语言代码的内存的开始地址。通常,这些地址对用户而言既不重要,也没有什么用处,但对程序而言,却很有用。例如:可以编写一个将另一个函数的地址作为参数的函数,这样第一个函数将能够找到第二个函数,并运行它,与直接调用另一个函数相比,这种方法很笨拙,但它允许在不同的时间传递不同函数的地址,这意味着可以在不同的时间使用不同的函数。
获取函数地址的方法很简单:只要使用函数名(后面不跟参数)即可。也就是说,如果think()是一个函数,那么think就是函数的地址。
要将函数作为参数进行传递,必须传递函数名。一定要区分传递的是函数的地址函数函数的返回值。
process(think); //passes address of think() to process
thought(think()); //passes return values of think() to thought()
声明函数指针:
声明指向某种数据类型的指针时,必须指定指针指向的类型,同样,声明指向函数的指针时,也必须指定指针指向的函数类型,这意味着声明应指定函数的返回类型以及函数的特征标(参数列表),也就是说,声明应该像函数原型那样支出有关函数的信息。
double pam(int);
//则正确的指针类型如下:
double (*pt)(int);
这与pam()声明类似,这是将pam替换为了(pf),由于pam是函数,因此*pf也是函数,而如果(pf)是函数,则pf就是函数指针。
提示:通常,要声明指向特定类型的函数的指针,可以首先编写这种函数的原型,然后用(*pf)替换函数名,这样pf就是函数指针。
#include <iostream>
double betsy(int);
double pam(int);
void estimate(int lines,double (*pf)(int));
int main()
{
using namespace std;
int code;
cout<<"How many lines of code do you need? ";
cin>>code;
cout<<"Here's Betsy's estimate:\n";
estimate(code,betsy);
cout<<"Here's Pam's estimate:\n";
estimate(code,pam);
return 0;
}
double betsy(int lns)
{
return 0.05 *lns;
}
double pam(int lns)
{
return 0.03*lns+0.0004*lns*lns;
}
void estimate(int lines,double(*pf)(int))
{
using namespace std;
cout<<lines<<" lines will take ";
cout<<(*pf)(lines)<<"hour(s)\n ";
}
上述是函数指针的使用范例。
深入探讨函数指针
在C++11中,我们可以使用auto来简单定义一个函数指针。
如:
const double *(p1)(const double*,int);
//可以在定义的时候初始化
const double *(p1)(const double*,int)=f1;
//使用auto关键字自动判断类型
auto p2= f1 ; //等价上述定义