函数调用操作(c++语法中的左右小括号)可以被重载,STL的特殊版本都以仿函数形式呈现。如果对某个class进行operator()重载,它就成为一个仿函数。
#include <iostream> using namespace std; template<class T> struct Plus { T operator()(const T& x, const T& y)const { return x + y; } }; template<class T> struct Minus { T operator()(const T& x, const T& y)const { return x - y; } }; int main() { Plus<int>plusobj; Minus<int>minusobj; cout << plusobj(3, 4) << endl; cout << minusobj(3, 4) << endl; //以下直接产生仿函数的临时对象,并调用 cout << Plus<int>()(43, 50) << endl; cout << Minus<int>()(43, 50) << endl; system("pause"); return 0; }
产生临时对象的方法:在类型名称后直接加一对小括号,并可指定初值。stl常将此技巧应用于仿函数与算法的搭配上。
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* template <class InputIterator,class Function> Function for_each(InputIterator first, InputIterator last, Function f) { for (; first != last; ++first) { f(*first); } return f; } */ template <typename T> class print { public: void operator()(const T& elem) { cout << elem << ‘ ‘ << endl; } }; 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>()); system("pause"); return 0; }
静态常量整数成员在class内部直接初始化,否则会出现链接错误。
#include <iostream> #include <vector> #include <algorithm> using namespace std; template <typename T> class testClass { public: static const int a = 5; static const long b = 3L; static const char c = ‘c‘; static const double d = 100.1; }; int main() { cout << testClass<int>::a << endl; cout << testClass<int>::b << endl; cout << testClass<int>::c << endl; //下面的语句出错,带有类内初始值设定项的静态数据成员必须具有不可变的常量整型 cout << testClass<int>::d << endl; system("pause"); return 0; }
increment(++)实现(前置式及后置式),dereference(*)实现
#include <iostream> #include <vector> #include <algorithm> 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->m_i); return temp; } //取值 int& operator*() const { return (int&)m_i; //下面的语句会出错,因为将int&类型的引用绑定到const int类型的初始值设定项 //return 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; system("pause"); return 0; }
时间: 2024-11-09 05:58:17