临时对象
临时对象,也称为无名对象。 通常会在两种情况下产生。
(1) 传值(pass by value)
隐式类型转换会产生临时变量 例如:int(8) 相当于调用了构造函数,但是没有指定名称。
可以用于仿函数和算法的搭配上 ,所以什么是仿函数。
仿函数(functor),就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了。
template < typename T>
class print
{
public:
void operator()(const T& elem)
{ cout << elem << ' '; }
};
int main()
{
int ia[6] = { 0,1,2,3,4,5 };
vector< int > iv(ia, ia+6);
for_each(iv.begin(), iv.end(), print<int>());
}
此处print就是一个临时对象,不是函数调用。
(2)函数返回值
在调用一个函数时,函数返回临时变量。
int max(int a, int b)
{
if(a > b) return a;
else return b;
// return a+b;也是
}
在这里函数返回的是一个临时变量。此处与STL相关不大,不做过多讨论。(提一句,函数中声明的对象,在函数结束后会销毁,因此尽量不要有返回函数中声明变量的地址。属于未定义行为。结果视编译器而定。)
静态常量整数成员初始化
C++中静态常量整数变量可以在类中初始化,例如int,long ,double,char 而string则不可以。静态整数变量也是不可的。
(静态变量在类中初始化,一定要注意有没有常量整数等条件)
template < typename T>
class node
{
public:
static const int a = 1;
static const long b = 3L;
static const char c = 'c';
static int d;
//static const string s = ""; 不行
//static int d = 4;不行
};
template<typename T> int node<T>::d = 0;
int main()
{
cout << node<int>::a << endl;
cout << node<int>::b << endl;
cout << node<int>::c << endl;
cout << node<int>::d << endl;
return 0;
}
操作符 increment/decrement/dereferencr
前进后退取值操作符,每个迭代器都有前进和取值操作符。都有非常规律的写法,需要重载++i i++ *i这些。需要重载时可以参考标准写法。
前闭后开表示法
STL的所有容器都是前闭后开的,可以用.begin()和.end()获取 即[.begin,.end) 可以采用以下方式去遍历。
for(<>::iterator it = *.begin;it != *.end() ; it++ )
二分 find 等算法返回的值也是按照这种规则的。
function call 操作符(operator() )
调用操作也可以被重载。准备来说不可以重载只有五个。
. (成员访问运算符)
.* (成员指针访问运算符)
:: (域运算符)
sizeof (长度运算符)
?: (条件运算符)
在STL算法中,可以根据默认的情况进行计算,也可以根据自定义的进行计算。
例如 qsort(c函数) sort(STL函数) 都可以
int cmp(int a, int b)
{
return a<b;
}
sort(z, z+n, cmp);
lambda 表达式
sort(a, a+n, [](int a,int b){return a<b;});
但是这种情况下虽然完成了功能,但是却不具备可适配性。
之前临时对象所说的仿函数,加以修改就可,而且使用起来与普通函数无异。如何修改后面讨论。
template <class T>
struct plus {
T operator()(const T& x, const T& y) const { return x + y; }
};
plus<int> pl;
cout << pl(10, 20) << endl; //30
cout << plus<int>(10,20) << endl; // 30