如何使用abstract base class模擬interface? (C/C++) (.NET) (C++/CLI)

interface是OO很重要的概念,也是實現abstraction的方法之一,C#、Java都另外提供了interface這個keyword,C++並沒有interface,必須用abstract base class模擬interface,但C++/CLI在這部分和ISO C++語法不太一樣。

C++/CLI的abstract base class的定義是:必須在abstract base class加上abstract,並包含一個以上的pure virtual function,除此之外,derived class的member function必須加上virtual和override。

 1 /* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : AbstractBaseClass.cpp
 5Compiler    : Visual C++ 8.0 / C++/CLI
 6Description : Demo how to use abstract base class simulate interface
 7Release     : 03/16/2007 1.0
 8*/

 9 #include  " stdafx.h "
10
11 using   namespace  System;
12
13 //  abstract base class
14 //  abstract keyword!!
15 public   ref   class  Student  abstract   {
16public:
17  String ^name; 
18
19public:
20  virtual String ^Job() = 0;
21}
;
22
23 public   ref   class  Bachelor :  public  Student  {
24public:
25  Bachelor() {
26    this->name = "N/A";
27  }

28    
29  Bachelor(String ^name) {
30    this->name = name;
31  }

32    
33public:
34  // virtual and override keyword
35  virtual String ^Job() override {
36    return "Study";
37  }

38}
;
39
40 int  main()  {
41  Bachelor ^John = gcnew Bachelor("John");
42  Console::WriteLine(John->Job());
43}


執行結果

Study


什麼是pure virtual function呢?20行

virtual  String  ^ Job()  =   0 ;


將function名稱加上=0後,則為pure virtual function,此function必須被derived class重新override定義。

值得注意的是15行

public   ref   class  Student  abstract   {


多了abstract字眼,這是C++/CLI和ISO C++不同之處。

35行derived class要override的member function

virtual  String  ^ Job()  override   {
  
return "Study";
}


前面必須加上virtual,後面必須加上override,這些ISO C++都不需要。

Conclusion
C++沒有interface,但只要透過abstract base class這個小技巧,仍可實現OO的interface概念,但這部分C++/CLI和ISO C++語法差異甚大。

See Also
(原創) 如何使用abstract base class模擬interface? (初級) (C++)

你可能感兴趣的:(interface)