handler2(70);
This results in Fun3()for objbeing called with an argument value of 70, so the output is:
Function3 called with value 71
The value stored in the value field for objis 1 because you create the object using the default constructor. The statement in the body of Fun3()adds the value field to the function argument - hence the 71 in the output.
Because they are both of the same type, you could combine the invocation list for handlerwith the list for the handler2delegate:
Handler^ handler = gcnew Handler(HandlerClass::Fun1); // Delegate object
Chapter 9: Class Inheritance and Virtual Functions
handler += gcnew Handler(HandlerClass::Fun2); HandlerClass^ obj = gcnew HandlerClass; Handler^ handler2 = gcnew Handler (obj, &HandlerClass::Fun3); handler += handler2;
Here you recreate handlerto reference a delegate that contains pointers to the static Fun1()and Fun2() functions. You then create a new delegate referenced by handlerthat contains the static functions plus the Fun3()instance function for obj. You can now invoke the delegate with the statement:
handler(50);
This results in the following output:
Function1 called with value 50 Function2 called with value 50 Function3 called with value 51
As you see, invoking the delegate calls the two static functions plus the Fun3()member of obj, so you can combine static and non-static functions with a single invocation list for a delegate.
Let's put some of the fragments together in an example to make sure it does really work.
Try It Out Creating and Calling Delegates
Here's a potpourri of what you have seen so far about delegates:
// Ex9_17.cpp : main project file. // Creating and calling delegates
#include "stdafx.h"
using namespace System;
public ref class HandlerClass { public:
static void Fun1(int m)
{ Console::WriteLine(L"Function1 called with value {0}", m); } static void Fun2(int m)
{ Console::WriteLine(L"Function2 called with value {0}", m); } void Fun3(int m)
{ Console::WriteLine(L"Function3 called with value {0}", m+value); } void Fun4(int m)
{ Console::WriteLine(L"Function3 called with value {0}", m+value); } HandlerClass():value(1){} HandlerClass(int m):value(m){}
Chapter 9: Class Inheritance and Virtual Functions
protected: int value; };
public delegate void Handler(int value); // Delegate declaration
int main(array ^args)
{ Handler^ handler = gcnew Handler(HandlerClass::Fun1); // Delegate object Console::WriteLine(L"Delegate with one pointer to a static function:");
handler->Invoke(90); handler += gcnew Handler(HandlerClass::Fun2); Console::WriteLine(L"
Delegate with two pointers to static functions:");
handler->Invoke(80); HandlerClass^ obj = gcnew HandlerClass; Handler^ handler2 = gcnew Handler (obj, &HandlerClass::Fun3); handler += handler2; Console::WriteLine(L"
Visual Studio C++ 2008 Part 2
Comenzar desde el principio
