括号运算符的重载

今天,读一段代码,发现了一段非常诡异的代码,我把它列在下面:
Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
{
    po::Options opts;
  opts.addOptions()
  ("help", do_help, false, "this help text")
  ("c", po::parseConfigFile, "configuration file name")
  
  ("InputFile,i",     cfg_InputFile,     string(""), "original YUV input file name")
  ("BitstreamFile,b", cfg_BitstreamFile, string(""), "bitstream output file name")
  ("ReconFile,o",     cfg_ReconFile,     string(""), "reconstructed YUV output file name")
  ("LambdaModifier0,-LM0", m_adLambdaModifier[ 0 ], ( double )1.0, "Lambda modifier for temporal layer 0")
  ("LambdaModifier1,-LM1", m_adLambdaModifier[ 1 ], ( double )1.0, "Lambda modifier for temporal layer 1")
  ("LambdaModifier2,-LM2", m_adLambdaModifier[ 2 ], ( double )1.0, "Lambda modifier for temporal layer 2")
  ("LambdaModifier3,-LM3", m_adLambdaModifier[ 3 ], ( double )1.0, "Lambda modifier for temporal layer 3")
  ("SourceWidth,-wdt",      m_iSourceWidth,  0, "Source picture width")
  ("SourceHeight,-hgt",     m_iSourceHeight, 0, "Source picture height")
... ...
;
... ...
}


opts.addOptions()

("help", do_help, false, "this help text")

("c", po::parseConfigFile, "configuration file name")

... ...

;

这么一段代码,令我百思不得其解,一个函数后面没有分号,还加了几个括号并列,在几个括号后面是分号。

查询源码发现addOptions()函数返回一个Options类的对象,而且在这个类里面重载了运算符()并且括号的返回值也是一个Options类的对象。查询《C++ primer》知道,有一种叫做函数对象的东东,就是在重载括号运算符的情况下,可以使用对象名+(参数)的方式来调用。于是做个试验的小程序:

Test.h

#ifndef _TESt2_H_
#define _TEST2_H_
#include <string>
class test
{
public:
	test(){}
	~test(){}
	
	test& operator ()(const std::string& _name,const std::string _dest = "")
	{
		name = _name;
		dest = _dest;
		return *this;
	}
	inline	std::string getName(){return name;}
	inline std::string getDest(){return dest;}
private:
	std::string name;
	std::string dest;
};

#endif

Test.cpp

#include "test2.h"


main.cpp

#include "test2.h"
#include <iostream>
int main()
{//.addoption()
	test Ctest;
	Ctest
	("1","a")	
	("2","b");//.operator ()	
	//("3","c");
	std::cout<<"name:"<<Ctest.getName()<<" dest:"<<Ctest.getDest()<<std::endl;
}


结果

括号运算符的重载_第1张图片

你可能感兴趣的:(String,File,input,lambda,layer,output)