C++ 模板函數(shù)純虛函數(shù)和Java對比

多態(tài)(虛函數(shù))框全。 動態(tài)多態(tài)(程序的角度上:程序在運行期間才能確定調(diào)用哪個類的函數(shù) == 動態(tài)多態(tài)的范疇)

Java語言默認支持多態(tài)
C++默認關(guān)閉多態(tài),怎么開啟多態(tài)汁针? 虛函數(shù) 在父類上給函數(shù)增加 virtual關(guān)鍵字

#include <iostream>
using namespace std;

// Android標準
class BaseActivity {
public:
     virtual void onStart() {
        cout << "BaseActivity onStart" << endl;
    }
};

class HomeActivity : public BaseActivity {
public:
    void onStart() { // 重寫父類的函數(shù)
        cout << "HomeActivity onStart" << endl;
    }
};

class LoginActivity : public BaseActivity {
public:
    void onStart() { // 重寫父類的函數(shù)
        cout << "LoginActivity onStart" << endl;
    }
};

// 在此函數(shù) 體系多態(tài)术辐,例如:你傳入HomeActivity,我就幫你運行HomeActivity
void startToActivity(BaseActivity * baseActivity) {
    baseActivity->onStart();
}

int main() {
    // TODO 第一版本
    HomeActivity *homeActivity = new HomeActivity();
    LoginActivity *loginActivity = new LoginActivity();

    startToActivity(homeActivity);
    startToActivity(loginActivity);

    if (homeActivity && loginActivity) delete homeActivity; delete loginActivity;


    cout << endl;


    // TODO 第二個版本
    BaseActivity * activity1 = new HomeActivity();
    BaseActivity * activity2 = new LoginActivity();
    startToActivity(activity1);
    startToActivity(activity2);


    // TODO 拋開 C++ 拋開Java 等等施无,請問什么是多態(tài)辉词? 父類的引用指向之類的對象,同一個方法有不同的實現(xiàn)猾骡,重寫(動態(tài)多態(tài))和   重載(靜態(tài)多態(tài))

    return 0;
}

靜態(tài)多態(tài) (編譯期已經(jīng)決定瑞躺,調(diào)用哪個函數(shù)了,這個就屬于靜態(tài)多態(tài)的范疇) 重載(靜態(tài)多態(tài))

#include <iostream>

using namespace std;

void add(int number1, int number2) {
    cout << number1 + number2 << endl;
}

void add(float number1, float number2) {
    cout << number1 + number2 << endl;
}

void add(double number1, double number2) {
    cout << number1 + number2 << endl;
}

int main() {
    add(10000, 10000);
    add(1.9f, 2.8f);
    add(545.4, 654.54);

    return 0;
}

純虛函數(shù)(Java版抽象類)

// C++純虛函數(shù)(C++沒有抽象類)  相當于 Java的抽象類  為了更好理解

#include <iostream>
using namespace std;

// 抽象類/純虛函數(shù): 分為:1.普通函數(shù)兴想, 2.抽象函數(shù)/純虛函數(shù)
class BaseActivity {
private:
    void setContentView(string layoutResID) {
        cout << "XmlResourceParser解析布局文件信息... 反射" << endl;
    }

public:
    // 1.普通函數(shù)
    void onCreate() {
        setContentView(getLayoutID());

        initView();
        initData();
        initListener();
    }

    // 純虛函數(shù)是必須繼承的(如果子類沒有重寫純虛函數(shù)幢哨,子類就是抽象類), 虛函數(shù)是不是不必須的

    // 2.抽象函數(shù)/純虛函數(shù)
    // virtual string getLayoutID(); // 虛函數(shù)
    virtual string getLayoutID() = 0; // 純虛函數(shù)
    virtual void initView() = 0;
    virtual void initData() = 0;
    virtual void initListener() = 0;
};

// 子類 MainActivity
class MainActivity : public BaseActivity { // MainActivity如果沒有重新父類的純虛函數(shù)嫂便,自己就相當于 抽象類了

    string getLayoutID() {
        return "R.layout.activity_main";
    }

    void initView()  {
        // Button btLogin = findViewById(R.id.bt_login);
        // Button btRegister = findViewById(R.id.bt_register);
        // TextView tvInfo = findViewById(R.id.tv_info);
        // ... 省略
    }

    void initData() {
        // tvInfo.setText("info...");
        // ... 省略
    }

    void initListener() {
        /*btLogin.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       // 點擊做事情
                   }
               });*/
        // ... 省略
    }
};

// 子類 HomeActivity
class HomeActivity : public BaseActivity { // MainActivity如果沒有重新父類的純虛函數(shù)捞镰,自己就相當于 抽象類了

    string getLayoutID() {
        return "R.layout.activity_home";
    }

    void initView()  {
        // Button btLogin = findViewById(R.id.bt_login);
        // Button btRegister = findViewById(R.id.bt_register);
        // TextView tvInfo = findViewById(R.id.tv_info);
        // ... 省略
    }

    void initData() {
        // tvInfo.setText("info...");
        // ... 省略
    }

    void initListener() {
        /*btLogin.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       // 點擊做事情
                   }
               });*/
        // ... 省略
    }
};

// 子類 LoginActivity
class LoginActivity : public BaseActivity { // MainActivity如果沒有重新父類的純虛函數(shù),自己就相當于 抽象類了

    string getLayoutID() {
        return "R.layout.activity_login";
    }

    void initView()  {
        // Button btLogin = findViewById(R.id.bt_login);
        // Button btRegister = findViewById(R.id.bt_register);
        // TextView tvInfo = findViewById(R.id.tv_info);
        // ... 省略
    }

    void initData() {
        // tvInfo.setText("info...");
        // ... 省略
    }

    void initListener() {
        /*btLogin.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       // 點擊做事情
                   }
               });*/
        // ... 省略
    }
};

int main() {

    // 錯誤:抽象類型 MainActivity 絕對不能實例化
    // MainActivity mainActivity;

    // 重新了父類所有的純虛函數(shù)
    MainActivity mainActivity;

    return 0;
}

虛函數(shù) 純虛函數(shù) 全純虛函數(shù)(C++沒有接口) 等價于 6.全純虛函數(shù)(Java版接口)毙替。

#include <iostream>
using namespace std;

class Student {
    int _id;
    string name;
    int age;
};

// 此類所有的函數(shù) 岸售,都是純虛函數(shù),就相當于 Java的接口了
class ISudent_DB {
    virtual void insertStudent(Student student) = 0;
    virtual void deleteStudent(int _id) = 0;
    virtual void updateStudent(int _id, Student student) = 0;
    virtual Student queryByStudent(Student student) = 0;
};

// Java的實現(xiàn)類
class Student_DBImpl1 : public ISudent_DB {
public:
    void insertStudent(Student student) {
        // 插入操作厂画,省略代碼...
    }

    void deleteStudent(int _id) {
        // 刪除操作凸丸,省略代碼...
    }

    void updateStudent(int _id, Student student) {
        // 更新操作,省略代碼...
    }

    Student queryByStudent(Student student) {
        // 查詢操作袱院,省略代碼...
    }
};

// Java的實現(xiàn)類
class Student_DBImpl2 : public ISudent_DB {
public:
    void insertStudent(Student student) {
        // 插入操作甲雅,省略代碼...
    }

    void deleteStudent(int _id) {
        // 刪除操作解孙,省略代碼...
    }

    void updateStudent(int _id, Student student) {
        // 更新操作,省略代碼...
    }

    Student queryByStudent(Student student) {
        // 查詢操作抛人,省略代碼...
    }
};

// Java的實現(xiàn)類
class Student_DBImpl3 : public ISudent_DB {
public:
    void insertStudent(Student student) {
        // 插入操作弛姜,省略代碼...
    }

    void deleteStudent(int _id) {
        // 刪除操作,省略代碼...
    }

    void updateStudent(int _id, Student student) {
        // 更新操作妖枚,省略代碼...
    }

    Student queryByStudent(Student student) {
        // 查詢操作廷臼,省略代碼...
    }
};

int main() {
    Student_DBImpl1 studentDbImpl1;
    Student_DBImpl2 studentDbImpl2;
    Student_DBImpl3 studentDbImpl3;

    cout << "Success" << endl;

    return 0;
}

模版函數(shù)(Java版泛型)。 C++沒有泛型 C++的模板函數(shù) 非常類似于 Java的泛型

#include <iostream>

using namespace std;

// 加分合集  int double float ... 你都要考慮绝页,你是不是要定義很多的 函數(shù)
/*void addAction(int n1, int n2) {
    cout << "addAction(int n1, int n2):" << n1 + n1 << endl;
}

void addAction(float n1, float n2) {
    cout << "addAction(int n1, int n2):" << n1 + n1 << endl;
}

void addAction(double n1, double n2) {
    cout << "addAction(int n1, int n2):" << n1 + n1 << endl;
}*/

// 模板函數(shù)  == Java的泛型解決此問題
template <typename TT>
void addAction(TT n1, TT n2) {
    cout << "模板函數(shù):" << n1 + n2 << endl;
}

int main() {
    addAction(1, 2);
    addAction(10.2f, 20.3f);
    addAction(545.34, 324.3);
    addAction<string>("AAA", "BBB");

    /*addAction(2, 324.3);
    addAction(54, 324.3f);*/
    return 0;
}

C++ 回調(diào)寫法類比Java

//回調(diào)荠商。  Java的登錄 簡單的 接口

#include <iostream>
using namespace std;

// 登錄成功的Bean
class SuccessBean {
public:
    string username;
    string userpwd;

    SuccessBean(string username, string userpwd)
    :username(username), userpwd(userpwd) {}
};

// 登錄響應(yīng)的接口  成功,錯誤
class ILoginResponse {
public:
    // 登錄成功
    virtual void loginSuccess(int code, string message, SuccessBean successBean) = 0;

    // 登錄失敗
    virtual void loginError(int code, string message) = 0;
};

// 登錄的API動作
void loginAction(string name, string pwd, ILoginResponse & loginResponse) {
    if (name.empty() || pwd.empty()) {
        cout << "用戶名或密碼為空!" << endl;
        return;
    }

    if ("ahehehehe" == name && "wdddd" == pwd) {
        loginResponse.loginSuccess(200, "登錄成功", SuccessBean(name, "恭喜你進入"));
    } else {
        loginResponse.loginError(404, "登錄錯誤续誉,用戶名或密碼錯誤...");
    }
}

// 寫一個實現(xiàn)類莱没,繼承接口
// 接口實現(xiàn)類
class ILoginResponseImpl : public ILoginResponse {
public:
    // 登錄成功
    void loginSuccess(int code, string message, SuccessBean successBean) {
        cout << "恭喜登錄成功 " << "code:" << code << " message:" << message
        << "successBean:" << successBean.username << "," << successBean.userpwd << endl;
    }

    // 登錄失敗
    void loginError(int code, string message) {
        cout << " 登錄失敗 " << "code:" << code << " message:" << message << endl;
    }
};

int main() {

    // 做實驗
    // Allocating an object of abstract class type 'ILoginResponse'
    // 正在分配抽象類型為ILoginResponse的對象  不能被實例化
    // 糾結(jié):為什么不可以
    // 1.他不是Java的接口,C++也沒有接口酷鸦,他只是像接口而已饰躲。
    // 2.他也不是抽象類,C++也沒有抽象類臼隔,他只是像抽象類而已嘹裂。
    // 3.他是純虛函數(shù)的類,此類決定不準你實例化  無論堆區(qū) 還是棧區(qū)
    /*new ILoginResponse() {
        // 登錄成功
        void loginSuccess(int code, string message, SuccessBean successBean) {

        }

        // 登錄失敗
        void loginError(int code, string message) {

        }
    }*/

    string username;
    cout << "請輸入用戶名.." << endl;
    cin >> username;

    string userpwd;
    cout << "請輸入密碼.." << endl;
    cin >> userpwd;

    ILoginResponseImpl iLoginResponse;
    loginAction(username, userpwd, iLoginResponse);

    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載摔握,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者寄狼。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市氨淌,隨后出現(xiàn)的幾起案子泊愧,更是在濱河造成了極大的恐慌,老刑警劉巖盛正,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拼卵,死亡現(xiàn)場離奇詭異,居然都是意外死亡蛮艰,警方通過查閱死者的電腦和手機腋腮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來壤蚜,“玉大人即寡,你說我怎么就攤上這事⊥嗨ⅲ” “怎么了聪富?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長著蟹。 經(jīng)常有香客問我墩蔓,道長梢莽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任奸披,我火速辦了婚禮昏名,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘阵面。我一直安慰自己轻局,他們只是感情好,可當我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布样刷。 她就那樣靜靜地躺著仑扑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪置鼻。 梳的紋絲不亂的頭發(fā)上镇饮,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天,我揣著相機與錄音箕母,去河邊找鬼储藐。 笑死,一個胖子當著我的面吹牛司蔬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播姨蝴,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼俊啼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了左医?” 一聲冷哼從身側(cè)響起授帕,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎浮梢,沒想到半個月后跛十,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡秕硝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年芥映,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片远豺。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡奈偏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出躯护,到底是詐尸還是另有隱情惊来,我是刑警寧澤,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布棺滞,位于F島的核電站裁蚁,受9級特大地震影響矢渊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜枉证,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一矮男、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧刽严,春花似錦昂灵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至倒脓,卻和暖如春撑螺,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背崎弃。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工甘晤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人饲做。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓线婚,卻偏偏與公主長得像,于是被迫代替她去往敵國和親盆均。 傳聞我的和親對象是個殘疾皇子塞弊,可洞房花燭夜當晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容