c++繼承、多態以及與java的行為差異之處

來源:互聯網
上載者:User

標籤:art   code   end   本質   tchar   clu   std   highlight   article   

對於物件導向而言,多態是最有用的基本特性之一,相對於函數指標,易用得多。下面看下c++繼承和多態行為的基本特性,最後說明下和java的基本差別。

首先定義父類和子類。

base.h

#pragma onceclass Base{public:    int i;    Base(void);    ~Base(void);    virtual void testDynCast();};

base.cpp

#include "stdafx.h"#include "Base.h"#include <iostream>using namespace std;Base::Base(void){}Base::~Base(void){}void Base::testDynCast() {cout << i << endl;}

Derived.h

#pragma once#include "base.h"class Derived :    public Base{public:    void testDynCast();    Derived(void);    ~Derived(void);};

Derived.cpp

#include "stdafx.h"#include "Derived.h"#include <iostream>using namespace std;Derived::Derived(void){}Derived::~Derived(void){}void Derived::testDynCast() {    cout << (i * i) << endl;}

基本使用:

int _tmain(int argc, _TCHAR* argv[]){    //多態測試    Derived derived = Derived();    derived.i = 100;    derived.testDynCast();    Base* dp1 = &derived;    // 繼承測試    if(Derived *dp = dynamic_cast<Derived*>(dp1)) {        dp->testDynCast();    }    Base base = Derived();    base.i = 100;    base.testDynCast();    dp1 = &base;    // 繼承測試    if(Derived *dp = dynamic_cast<Derived*>(dp1)) {        dp->testDynCast();    }    cout << "繼承測試結束" << endl;    // 繼承測試結束}

輸出如下:

1000010000100繼承測試結束

從上面的代碼和結果可以看出,c++跟java的要求或差別至少包括:

1、c++不要求類名和檔案名稱保持一致,不過保持一致總是一個好習慣;

2、對於非抽象類別,在定義對象時所使用的c++類型決定了實際類型,至於具體賦值的是什麼類型應該是自動截掉了(雖然沒有本質性差別,但是對於習慣了java的人員而言,明顯多此一舉)。

3、為了使用多態,必須至少有一個方法聲明為虛函數。

 剛想到反射(一般而言,如果要寫一個架構比如RPC的話,掌握反射是必不可少的)的問題,總體而言,可以參考下面兩個連結:

https://technet.microsoft.com/zh-cn/library/7k3448yy.aspx

http://www.tuicool.com/articles/VJRVVrQ

實現本身而言,應該沒有想象那麼難。

c++繼承、多態以及與java的行為差異之處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.