字符串
读取未知数量的string对象,碰到空白就会停止将读到的内容存到string对象中
int main()
{
string = word;
while(cin>>word)
cout<<word<<endl;
return 0;
}
使用getline读取一整行, getline函数只会碰到换行符才会将读的内容存入到string对象中(抛弃换行符)
int main()
{
string word;
while(getline(cin, word))
cout<<word<<endl;
return 0;
}
对于string类的成员函数size(),返回的类型是一个unsigned,所以最好不要和int在一个表达式中混合使用。
使用**“ ”**括起来的叫做字符串字面值,类型上是由常量字符构成的数组,结尾处还有一个空字符,实际长度要比它的内容多1。
vector
访问vector可以使用for范围语句
vector<int> vect1{10, 0};
for (auto i : vect1)
cout<<i<<endl;
对于vector来说,不能通过下标去访问vector中不存在的元素,只能通过push_back()方法。尽量不要使用下标去访问vector,避免下标越界。尽可能使用for范围语句访问。
vector<int> vect1;
for(decltype(vect1.size()) i=0; i != vect1.size(); ++i)
vect1[i] = i //错误,不能通过下标去访问vector中不存在的元素
vect1.push_back(i); //正确
默认实参
默认形参在函数定义和声明中药放置在没有默认参数的形参之后。
头文件
函数的声明,自定义的内联函数的定义,constexpr函数定义都放在头文件中。
函数指针
函数指针指向的是函数而非对象,函数指针指向的是特定的类型,函数的类型由返回类型和形参类型决定。
const放在成员函数的的形参后面是常量成员函数
常量成员函数中的this指针是一个指向常量的指针,所以常量成员函数不能改变调用它的对象的内容。
友元函数
友元函数在类里面需要进行声明,在类的外面也需要进行初始声明,但是有的编译器允许没有初始声明就可以调用友元函数。最好还是进行初始声明。
函数指针
- 当把函数作为实参时,可以直接使用函数名,会自动转换为指针
userBigger(s1, s2, lengthCompare)
- 也可以使用类型别名和decltype
//Func 和Func2是函数类型
typedef bool Func(const string &s1, const string &s2);
typedef decltype(lengthMore) Func2;
//FuncP 和FuncP2是函数指针类型
typedef bool (*Funcp)(const string &s1, const string &s2);
typedef decltype(lengthMore) *Funcp2;
只能返回函数类型的指针,不能够返回函数类型
using F = int(int *);
using PF = int (*)(int *);
PF f1(int);
F *f1(int);
如果我们明确知道要返回的函数哪一个
string::size_type sumLength(const string &s1, const string &s2);
string::size_type largerLength(const string &s3, const string &s4);
decltype(sumLength) *Func(const string &s5);
定义返回数组的指针的函数
函数不能返回数组,只能返回数组的指针,使用类型别名来定义返回数组指针的函数
typedef int arrT[10];
using arrT = int[10];
arrT *func(int i)
使用尾置指针类型
auto func(int i) -> int (*)[10];
使用decltype关键字
int old[] = [1,2,3,4,5];
int even[]=[4,5,6,7,8];
decltype(old) *func(int i){
return (i % 2)? &old:&even
}