c++调用基类的构造函数(模板类)
来源:互联网 发布:淘宝跑包 编辑:程序博客网 时间:2024/06/05 15:27
代码如下
#include <stdlib.h>#include <stdio.h>#include <iostream>using namespace std;template<class T>class Base{public:Base(T name);virtual void toString();protected:T id;};template<class T>Base<T>::Base(T n){printf("Base constructor!\n");id = n;}template<class T>void Base<T>::toString(){cout<<"my id is "<<id<<endl;}template<class T>class Derive:public Base<T>{public:Derive(T id);};template<class T>Derive<T>::Derive(T n):Base<T>(n){printf("Derive constructor!\n");}int main(void){Derive<int> d(5);d.toString();return 0;}
需要注意的是,派生类调用基类的构造函数是Base<T>(n)这样子的,要加上模板参数,不然会编译错误。
如果没有模板参数T,出现的错误是
../src/CTest.cpp: 在构造函数‘Derive<T>::Derive(T)’中:../src/CTest.cpp:41:24: 错误: 类‘Derive<T>’没有名为‘Base’的字段../src/CTest.cpp: In instantiation of ‘Derive<T>::Derive(T) [with T = int]’:../src/CTest.cpp:49:17: required from here../src/CTest.cpp:41:30: 错误: 对‘Base<int>::Base()’的调用没有匹配的函数../src/CTest.cpp:41:30: 附注: 备选是:../src/CTest.cpp:21:1: 附注: Base<T>::Base(T) [with T = int]../src/CTest.cpp:21:1: 附注: 备选需要 1 实参,但提供了 0 个../src/CTest.cpp:11:7: 附注: Base<int>::Base(const Base<int>&)../src/CTest.cpp:11:7: 附注: 备选需要 1 实参,但提供了 0 个make: *** [src/CTest.o] 错误 1
0 0
- c++调用基类的构造函数(模板类)
- 模板类的构造函数调用错误问题分析
- C++:派生类的默认构造函数和拷贝构造函数调用基类构造函数的机制(含程序验证)
- C++调用基类的构造函数
- 构造函数访问权限和基类构造函数,派生类的构造函数调用顺序
- 派生类构造函数和析构函数的调用顺序(C++)
- c++:在类的构造函数中调用另一个构造函数
- c++,派生类无法调用基类构造函数
- 调用基类构造函数
- 调用基类构造函数
- 小朋友学C++(10):子类构造函数调用父类构造函数
- 【C++】基类和派生类构造函数的调用顺序
- 【C++】基类与子类拷贝构造函数的调用顺序
- 类的构造函数调用其他构造函数
- 拷贝构造函数调用父类的构造函数
- [c++]类的构造函数
- C++-类的构造函数
- c++(1) 类模板/构造函数/捕获异常 实例
- 【BZOJ】【P1031】【字符加密Cipher】【题解】【后缀数组】
- camera中,软键盘遮挡问题
- EditText支持多行同时支持imeOptions设置
- 灰太狼抓羊
- cobar文档 - 后端数据源心跳
- c++调用基类的构造函数(模板类)
- php快速排序的实现
- Makefile的简介
- 在二进制文件中查找关键字
- ubuntu下软件安装及mysql的安装过程
- printk()函数
- linux磁盘目录结构
- Android SQLiteStatement 编译、执行 分析
- 安装MySQL (转)