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

C++ 模板類繼承:派生類正確調用基類構造函數

     編輯:C++ 入門

核心規則

派生類構造函數初始化列表中調用基類構造函數時,**必須帶上模板參數**:

template <class T>
class Derive : public Base<T> {
public:
    Derive(T n) : Base<T>(n) { } // 正確:Base<T>(n)
    // Derive(T n) : Base(n) { }  // 錯誤:缺少模板參數
};

完整可編譯範例

#include <iostream>
using namespace std;

template <class T>
class Base {
public:
    Base(T n) { cout << "Base constructor!\n"; id = n; }
    virtual void toString() { cout << "my id is " << id << '\n'; }
protected:
    T id;
};

template <class T>
class Derive : public Base<T>] {
public:
    Derive(T n) : Base<T>(n) { cout << "Derive constructor!\n"; }
};

int main() {
    Derive<int> d(5);
    d.toString();
    return 0;
}

錯誤訊息分析

錯誤:類‘Derive’沒有名為‘Base’的字段
錯誤:對‘Base::Base()’的調用沒有匹配的函數
備選:Base::Base(T) [with T = int] — 需要 1 實參

編譯器將 Base 視為非模板類別,找不到無參數構造函數。

記憶口訣

「模板繼承調基構,模板參數不能漏」

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