Chapter 9: Class Inheritance and Virtual Functions
The Sum()function is a public instance member of the ThisClassclass, so invoking the ubhdelegate will call the Sum()function for any object of this class type.
When you call an unbound delegate, the first argument is the object for which the functions in the invocation list are to be called, and the subsequent arguments are the arguments to those functions. Here's how you might call the ubhdelegate:
ThisClass^ obj = gcnew ThisClass(99.0);
ubh(obj, 5);
The first argument is a handle to a ThisClassobject that you created on the CLR heap by passing the value 99.0 to the class constructor. The second argument to the ubhcall is 5, so it results in the Sum() function being called with an argument of 5 for the object referenced by obj.
You can combine unbound delegates using the + operator to create a delegate that calls multiple functions. Of course, all the functions must be compatible with the delegate, so for ubhthey must be instance functions in the ThisClassclass that have one parameter of type intand a voidreturn type. Here's an example:
ubh += gcnew UBHandler(&ThisClass::Product);
Invoking the new delegate referenced by ubhcalls both the Sum()and Product()functions for an object of type ThisClass. Let's see it in action.
Try It Out Using an Unbound Delegate
This example uses the code fragments from the previous section to demonstrate the operation of an unbound delegate:
// Ex9_18.cpp : main project file.
// Using an unbound delegate
#include "stdafx.h"
using namespace System;
public ref class ThisClass { public:
void Sum(int n)
{ Console::WriteLine(L"Sum result = {0} ", value+n); } void Product(int n)
{ Console::WriteLine(L"product result = {0} ", value*n); } ThisClass(double v) : value(v){} private: double value;
Chapter 9: Class Inheritance and Virtual Functions
};
public delegate void UBHandler(ThisClass^, int value);
int main(array ^args) {
array^ things = { gcnew ThisClass(5.0),gcnew ThisClass(10.0), gcnew ThisClass(15.0),gcnew ThisClass(20.0), gcnew ThisClass(25.0)
}; UBHandler^ ubh = gcnew UBHandler(&ThisClass::Sum); // Create a delegate object // Call the delegate for each things array element for each(ThisClass^ thing in things)
ubh(thing, 3); ubh += gcnew UBHandler(&ThisClass::Product); // Add a function to the delegate // Call the new delegate for each things array element for each(ThisClass^ thing in things) ubh(thing, 2);
return 0; }
This example produces the following output:
Sum result = 8 Sum result = 13 Sum result = 18 Sum result = 23 Sum result = 28 Sum result = 7 product result = 10 Sum result = 12 product result = 20 Sum result = 17 product result = 30 Sum result = 22 product result = 40 Sum result = 27 product result = 50
How It Works
The UBHandlerdelegate type is declared by the following statement.
public delegate void UBHandler(ThisClass^, int value);
Visual Studio C++ 2008 Part 2
Start from the beginning
