I l @ ve RuBoard |
The __interface keyword can be used to create COM-style interfaces with a minimum of fuss and no IDL. This keyword is not specifically listed in the first part of this chapter because it applies to other technologies, too. However, when used in conjunction with the __gc managed C++ extension, it creates a managed interface. A simple interface is shown in Listing 1.4.5. Listing 1.4.5 managedif.cpp : A Simple Managed Interface#using <mscorlib.dll> using namespace System; __gc __interface IDoSomething { String * SayHello(); }; __gc class CDoSomething : public IDoSomething { String * SayHello() { return new String("Hello"); } }; void main() { CDoSomething* pD=new CDoSomething(); IDoSomething *pI=static_cast<IDoSomething*>(pD); String* s=pI->SayHello(); Console::WriteLine(s); } A big advantage to the combination of the managed object and the interface is that the compiler has support for ambiguous method names . If you have two interfaces with methods of the same name , you can identify which implementation goes with which interface. Listing 1.4.6 shows how to resolve ambiguous interfaces. Listing 1.4.6 Ambiguous.cpp : Resolving Ambiguous Interfaces#using <mscorlib.dll> using namespace System; __gc __interface IFirst { void TheMethod(); }; __gc __interface ISecond { void TheMethod(); }; __gc class AClass : public IFirst, public ISecond { void IFirst::TheMethod() { Console::WriteLine("Invoked IFirst::TheMethod"); } void ISecond::TheMethod() { Console::WriteLine("Invoked ISecond::TheMethod"); } }; void main() { AClass* c=new AClass(); IFirst *pF=static_cast<IFirst*>(c); ISecond *pS=static_cast<ISecond*>(c); pF->TheMethod(); pS->TheMethod(); } The class AClass distinguishes between the two interface definitions by specifying which of the TheMethod entries is being implemented. |
I l @ ve RuBoard |