Java Programmer learns C + + 's function pointers

Source: Internet
Author: User

The definition of a function pointer:



Header file: Function.h

The header defines the interface, defines the template method in the actual source file//The subsequent calling class only needs to implement a callback that overrides the Before,process,after method to implement the template method/*extern can be placed before a variable or function, To indicate the definition of a variable or function in another file, prompting the compiler to find its definition in other modules when it encounters this variable or function. */extern void (*before) (), extern void (*process) (int,int), extern void (*after) (), void my_function (int a,int b);


Source file Main.cpp

#include "function.h" #include <iostream>using namespace Std;extern void Dosth ();// The static tag for the method is scoped to the module (file) in the static void Before_pro () {cout << "Main.before_pro" << Endl;} static void Process_pro (int a, int b) {cout << "Main.process_pro" << Endl;} static void After_pro () {cout << "Main.after_pro" << Endl;} void My_function (int a, int b)//{//before ();//process (A, b);//after ();//}int Main () {before = Before_pro;process = Process_pro;after = after_pro;my_function (2,3);d osth (); return 0;}

Source file: Test.cpp

#include <iostream> #include "function.h" using namespace Std;void (*before) (); void (*process) (int, int); void (* After) (); static void Before_pro () {cout << "Test.before_pro" << Endl;} static void Process_pro (int a, int b) {cout << "Test.process_pro" << Endl;} static void After_pro () {cout << "Test.after_pro" << Endl;} void Dosth () {before = Before_pro;process = Process_pro;after = After_pro;my_function (2, 3);} void My_function (int a, int b) {before ();p rocess (A, b); after ();}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Programmer learns C + + 's function pointers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.