首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 派生類別存取模板化基類別成員的三種方法

     編輯:關於C++

問題

模板基類別的成員在派生類別中不可直接存取(this->member 或 member 編譯錯誤),因模板具現化可能移除該成員,編譯器無法於定義期驗證。

三種解決方法

  1. this->member:延後查找至實例化期,編譯器假設存在。
  2. using Base<T>::member;:引入基類別成員至派生類別作用域。
  3. Base<T>::member:顯式限定,**不建議**,會關閉虛擬函式動態綁定。

程式碼

/* test.cpp
 * Created on: 2014.04.18
 * Author: Spike
 */
#include <iostream>
#include <string>
#include <memory>
using namespace std;

class CompanyCaroline {
public:
    void sendCleartext(const string& msg) { cout << "Cleartext: " << msg << endl; }
    void sendEncrypted(const string& msg) { cout << "Encrypted: " << msg << endl; }
};

struct MsgInfo { string cleartext, encrypted; };

template<typename Company>
class MsgSender {
public:
    void sendClear(const MsgInfo& info) {
        Company c; c.sendCleartext(info.cleartext);
    }
    void sendSecret(const MsgInfo& info) {
        Company c; c.sendEncrypted(info.encrypted);
    }
};

template<typename Company>
class LoggingMsgSender : public MsgSender<Company> {
public:
    // using MsgSender<Company>::sendClear; // 方法二
    void sendClearMsg(const MsgInfo& info) {
        cout << "Log Begin : ";
        this->sendClear(info); // 方法一
        // MsgSender<Company>::sendClear(info); // 方法三,關閉虛擬綁定
    }
};

int main() {
    MsgInfo mi = {"Clear", "Encrypted"};
    LoggingMsgSender<CompanyCaroline> lms;
    lms.sendClearMsg(mi);
}

輸出

Log Begin : Cleartext: Clear

建議

優先使用 this-> 或 using 宣告,保留虛擬函式動態綁定特性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved