您的位置:首页 > 编程语言 > C语言/C++

C++回调函数 与 C# delegate

2016-05-28 10:42 417 查看
mypersion.h

#ifndef MY_PERSION_H_
#define MY_PERSION_H_
#include<string>
#include<iostream>
using namespace std;
class mypersion{
private:
int age;
string name;
int sex;

public :
mypersion(int age, string name, int sex);
//|第一个参数就是函数指针需要代入 返回值为void 函数签名为int ,string,int的函数
void callback(void (*callback)(int, string, int),int age,string name,int sex );
};
void setter(int age, string name, int sex);
#endif


mypersion.cpp

#include"mypersion.h"
mypersion::mypersion(int age, string name, int sex)
{
this->age = age;
this->name = name;
this->sex = sex;
}
void mypersion::callback(void(*callback)(int, string, int), int age, string name, int sex)
{
(*callback)(age, name, sex);
cout << "您更改了成员属性" << endl;
}
void setter(int age, string name, int sex)
{
cout << "有值改变了" << endl;
}


main.cpp

#include<iostream>
#include"mypersion.h"
using namespace std;
int main(int argc, char * argv[])
{
mypersion * p = new mypersion(19, "涵涵", 1);
p->callback(setter, 1, "涵涵", 1);
cout << "hello world" << endl;
while (1);
}



C# Delegate

mypersion.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cscallback
{
class mypersion
{
private
int age;
string name;
int sex;
public
mypersion(int age, string name, int sex) {
this.age = age;
this.name = name;
this.sex = sex;
}
public
void setter(int age,string name,int sex)
{
Console.WriteLine("调用了setter");
}
public
delegate void Func(int a,string n,int s);
public
static void CallBack(Func fun,int age,string name,int sex)
{
fun(age, name, sex);
}
}
}
program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cscallback
{
class Program
{
static void Main(string[] args)
{
mypersion p = new mypersion(1, "涵", 1);
mypersion.CallBack(p.setter,1,"x",1);
while(true);
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: