目录
5. 可以重载函数调用 操作符 ( operator() )
1. 临时对象的产生和运用
C++中所谓的临时对象是不可见的。只要产生一个non-heap对象,而且没有为它命名,便产生了一个临时对象。
临时对象通常发生于在:1. 当函数参数是按值传递时,会产生复制操作,产生临时对象。
2. 当发生隐式类型转换时,如const int & ci = 3.14;
3. 当函数返回对象的时候。
4. 刻意制造临时对象。int(8),shape(3,5);
临时对象的销毁: 1. 一般临时对象的有效生存周期为当前表达式。该表达式结束后,临时对象被销毁。
2. 当临时对象被引用后,直到引用被销毁后,临时对象被销毁。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
class print{
public:
void operator()(const T& elem)
{ cout<<elem<<' ';}
};
int main()
{
int ia[6]={1,2,3,4,5,6};
vector<int> iv(ia,ia+6);
//print<int>() 为临时对象
for_each(iv.begin(),iv.end(),print<int>() );
return 0;
}
2. 静态常量整数成员在class内部直接初始化
当class中含有静态常量整型成员,那么我们可以再class中直接赋予其初值。
template<typename T>
class testClass{
public:
static const int i=5;
static const long li=15L;
static const char c = 'c';
}
3. 递增、递减、取值 操作符
在递增和递减的操作中还分为前置式和后置式两种。
#include<iostream>
using namespace std;
class INT{
friend ostream& operator<<(ostream &os,const INT &i);
public:
INT(int i):m_i(i){}
INT & operator++ ()
{
++(this->m_i);
return *this;
}
const INT operator++ (int)
{
INT temp = *this;
++(*this);
return temp;
}
INT & operator-- ()
{
--(this->m_i);
return *this;
}
const INT operator-- (int)
{
INT temp = *this;
--(*this);
return temp;
}
int & operator*()const{
return (int&)m_i;
}
private:
int m_i;
};
ostream& operator<<(ostream &os,const INT & i)
{
os<<'['<<i.m_i<<']'<<endl;
return os;
}
int main()
{
INT I(5);
cout<<I++;
cout<<++I;
cout<<I--;
cout<<--I;
cout<<*I;
return 0;
}
4. 前闭后开区间表示法 [first,last)
任何一个STL算法,都需要获得由一对迭代器所标示的区间,用以表示操作范围。
这一对迭代器所标示的是个所谓的前闭后开区间,以[first,last)表示。整个实际范围从first开始,到last-1结束。
5. 可以重载函数调用 操作符 ( operator() )