STL靜多態和動多態小釋

來源:互聯網
上載者:User

#include <iostream>
#include <vector>
using namespace std;
/*用多態來實現的話需要
<1>定義時注意:
1.定義
class Base
{

 virtual ShowDemo() const = 0;
};
2.剝離抽象業務放到公用類中
3.讓 Derived1, Derived2都從Base 繼承而來
4.子類必須實現介面函數
<2>使用時注意
1.處理業務函數的參數只能使用 Base& 或者 Base* 方式傳遞對象地址,
  讓其在運行期判別類型找到對應函數
2.每次繼承增加一張虛表增加資源開銷。
*/
class Derived1
{
public:
 void ShowDemo() const { cout<<"Derived1::ShowDemo()"<<endl; }
};

class Derived2
{
public:
 void ShowDemo() const { cout<<"Derived2::ShowDemo()"<<endl; }
};

//使用模板演繹實參,直接在運行期就得到確定的物件類型
//只不過使用泛型,少了對ShowDemo做重載,但其實執行個體化了兩次
//因為僅僅針對於這一整類使用泛型可以,但是如果傳入的T為其他類型呢
//靜態檢測會發現問題,發現結構無此函數
template< typename T >
void ShowDemo( T const& t_g )
{
 t_g.ShowDemo();
}

template< typename T1, typename T2 >
void EffecEach( T1 const& t_g_1, T2 const& t_g_2 )
{
 t_g_1.ShowDemo();
 t_g_2.ShowDemo();
}

template < typename T >
void ShowDemoAll( vector<T> const& t_v_g )
{
 for( int i = 0; i < t_v_g.size(); i++ )
  t_v_g[i].ShowDemo(); //
}

void main()
{

 Derived1 t_d_1;
 Derived2 t_d_2;

 ShowDemo(t_d_2);
 ShowDemo(t_d_1);

 EffecEach( t_d_1, t_d_2 );
 vector<Derived2> coll;
 coll.push_back(t_d_2);
 ShowDemoAll(coll);
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.