括号运算符的重载

今天,读一段代码,发现了一段非常诡异的代码,我把它列在下面:
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;
}


结果


  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值