指针c++的模板数组

Template array of pointers c++?

本文关键字:数组 c++ 指针      更新时间:2023-10-16

大家好,在我的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>