指针c++的模板数组
Template array of pointers c++?
大家好,在我的c++程序中,我有四个类(A、B、c、D)
- A是基类
- B继承自A
- C继承自A
- D继承自B
所有这些都是模板类template<class Type>
,并且每个模板类都有一个打印方法,用于打印其私有成员及其继承的类的私有成员。
因此,B将打印B私人会员和A私人会员,C将打印C私人会员和A私人会员,D将打印其私人会员和B,A私人会员。
在主函数中,我想为类A创建一个指针数组,每个类的对象有3个位置,然后我想循环每个对象打印方法。
问题是,当我将类更改为模板类时,我收到一条错误消息,上面写着"我的类没有构造函数";但是他们确实有。
这是我的代码请帮助(注意,我为你评论了错误发生的地方):
#include <iostream>
#include <string>
using namespace std;
template <class Type>
class A
{
public:
virtual void print()
{
cout<<"the base class (A) private (x) is : "<<x<<endl;
}
A(Type X = 0)
{
x = X;
}
void setX(Type X)
{
x = X;
}
Type getX() const
{
return x;
}
private:
Type x;
};
template <class Type>
class B:public A
{
public:
B(Type X = 0,Type Y = 0)
{
setX(X);
y = Y;
}
void setY(Type Y)
{
y = Y;
}
Type getY() const
{
return y;
}
void print()
{
A::print();
cout<<"private (y) in class (B) is : "<<getY()<<endl;
}
private:
Type y;
};
template <class Type>
class C:public A
{
public:
C(Type X = 0,Type Z = 0)
{
setX(X);
z = Z;
}
void setZ(Type Z)
{
z = Z;
}
Type getZ() const
{
return z;
}
void print()
{
A::print();
cout<<"private (z) in class (C) is : "<<getZ()<<endl<<endl;
}
private:
Type z;
};
template <class Type>
class D:public B
{
public:
D(Type X = 0,Type Y = 0,Type W = 0)
{
setX(X);
setY(Y);
w = W;
}
void setW(Type W)
{
w = W;
}
Type getW() const
{
return w;
}
void print()
{
B::print();
cout<<"private (w) in class (D) is : "<<getW()<<endl;
}
private:
Type w;
};
void main()
{
A<int>* arrayOfPointers[3];
arrayOfPointers[0] = new B(1,100);//error here
arrayOfPointers[1] = new C(2,200);//error here
arrayOfPointers[2] = new D(3,300,3000);//error here
for(int i = 0 ; i<3;i++)
{
cout<<typeid(*arrayOfPointers[i]).name()<<" Print method : n"<<endl;
arrayOfPointers[i]->print();
cout<<"**********************n"<<endl;
}
}
您忘记了两件事:
1) 您的继承需要为它们从中继承的类指定模板参数。例如:
template <class Type>
class B : public A<Type>
{
...
}
2) 当您实例化类时,还需要提供模板参数:
arrayOfPointers[0] = new B<int>(1, 100);
arrayOfPointers[1] = new C<int>(2, 200);
arrayOfPointers[2] = new D<int>(3, 300, 3000);
然而,您也可以提供模板函数来从提供的参数实例化这些类,比如std库中的make_(…)方法:
template <class Type>
B<Type>* create_B(const Type& t1, const Type& t2)
{
return new B<Type>(t1, t2);
}
并像这样使用:
arrayOfPointers[0] = create_B(1, 100);
然而,请注意,这些方法正在创建指向已分配堆内存的原始指针,因此您有责任删除它(您可能会使用shared_ptrs或其他方法来克服这一问题,或者只返回一个对象等,但这实际上不是您的问题/我的答案的一部分)。
您从A
继承,但应该从特定的实例化A<T>
继承。也许是class B:public A<Type>
?
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '