c++如何用类Template创建对象

c++ how to create object with class Template

本文关键字:创建对象 Template 何用类 c++      更新时间:2023-10-16

我有以下代码。

Main.cpp:

Warehouse<Base<int>> arm(1, 1, 1, 1);
arm.createSubBase(1,1,1);

仓库.h:

private:
 vector<Base<T>*> whouse;
public :
 void createSubBase(int, int, int);
template <class T> 
void Warehouse<T>::createSubBase(int,int,int) {
  Base<T>* dN = new SubBase<T>(int,int,int,int); ***<-ERROR MESSAGE:" in file included from"***
     whouse.push_back(dN);
}

基本.h:

template <class T>
class Base {
private:
 int I,a,b,c;
public :
  Base(int,int,int,int);
}
template <class T>
Base<T>::Base(int i, int a, int b, int c) {
    this -> I = i;
    this -> a= a;
    this -> b= b;
    this -> c = c;
}

SubBase.h:

template <class T>
class SubBase: public Base<T> {
public:
  SubBase(int, int, int,int);
}
template <class T>
SubBase<T>::SubBase(int, int, int , int) : Depositos<T>(int,int,int,int) {...}

有人知道我为什么收到这个错误消息吗?我不明白为什么不让我创建Base<T> * b = new subbase<T> ( int , int , int );

函数参数需要是给出参数值的表达式,而不是像int这样的类型名称。所以有问题的线路应该是

Base<T>* dN = new SubBase<T>(a,b,c,d);

abcd替换为要传递给构造函数的任何参数。类似地,构造函数需要向其基类传递有效的参数(也需要使用正确的名称指定基类)。也许你想直接通过争论:

SubBase<T>::SubBase(int a, int b, int c, int d) : Base<T>(a,b,c,d) {...}

在类定义之后还缺少;

修复这些错误后,代码为我编译:http://ideone.com/mb0AOP