6、函数调用运算符重载.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //4.5.6 函数调用运算符重载
  2. //⚪函数调用运算符 () 也可以重载
  3. //⚪由于重载后使用的方式非常像函数的调用,因此称为仿函数
  4. //⚪仿函数没有固定写法,非常灵活
  5. #include <iostream>
  6. //打印输出类
  7. class MYPrint
  8. {
  9. public:
  10. //重载函数调用运算符
  11. void operator()(std::string test)
  12. {
  13. std::cout << test << std::endl;
  14. }
  15. };
  16. void MyPrint02(std::string test)
  17. {
  18. std::cout << test << std::endl;
  19. }
  20. void test01()
  21. {
  22. MYPrint myPrint;
  23. myPrint("Hello World"); //由于使用起来非常类似于函数调用,因此成为仿函数。
  24. MyPrint02("hello world");
  25. }
  26. //仿函数非常灵活,没有固定的写法
  27. //加法类
  28. class MyAdd
  29. {
  30. public:
  31. int operator()(int num1,int num2)
  32. {
  33. return num1 + num2;
  34. }
  35. };
  36. void test02()
  37. {
  38. MyAdd myadd;
  39. int ret = myadd(100, 100);
  40. std::cout << "ret = " << ret << std::endl;
  41. //匿名函数对象
  42. std::cout << MyAdd()(100, 100) << std::endl;
  43. }
  44. int main()
  45. {
  46. //test01();
  47. test02();
  48. system("pause");
  49. return 0;
  50. }