C ++入門書の5番目の注意事項(第14章オーバーロード操作と型変換)関数呼び出し演算子

1.定義

クラスが呼び出し演算子を定義している場合(関数呼び出し演算子がオーバーロードされている場合)、このクラスのオブジェクトは関数オブジェクトと呼ばれ、このクラスのオブジェクトは関数のように使用できます。

例えば。

struct absInt{
    
    
	int operator()(int val) const{
    
    
		return val < 0 ? -val : val;
	}
};

int i = -42;
absInt absObj;
int ui = absObj(i);	//i被传递给absObj.operator() 

2.機能

  • 関数呼び出し演算子は、メンバー関数として定義する必要があります。
  • 。クラスは、呼び出し演算子の複数の異なるバージョンを定義できます。これは、パラメーターの数またはタイプが異なる必要があります。
  • 。関数呼び出し演算子を持つクラスも状態を格納できるため、通常の関数よりも柔軟性があります。
  • 。関数オブジェクトは、一般的なアルゴリズムの実際のパラメータとしてよく使用されます。
class PrintString
{
    
    
public:
    PrintString(ostream &o = cout, char c = ' '):
        os(o), sep(c) {
    
     }
    void operator()(const string &s) const
    {
    
    
        os << s << sep;
    }

private:
    ostream &os;   // stream on which to write
    char sep;      // character to print after each output
};
 
 string strText = "test";
 PrintString printer;  // uses the defaults; prints to cout
 printer(strText);     // prints s followed by a space on cout

  PrintString printer2(cerr, '_');
  printer2(strText);		//cerr中打印s,后面跟一个换行符
 
  //函数对象常常作为泛型算法的实参
  std::vector<string> vecStr = {
    
    "a1", "b1"};
  for_each(vecStr.begin(), vecStr.end(), PrintString(cerr, '-'));

出力結果:

test test_a1-b1-

[見積もり]

[1]コードfunctionObject.h

おすすめ

転載: blog.csdn.net/thefist11cc/article/details/114160509