你好球员在我的C++程序我有四个类(A,B,C,d)模板指针C++数组?
- A是基类
- 乙从A
- Ç继承甲
- d继承的B
他们都继承是模板类template<class Type>
和他们每个人都有,它打印的私有成员,它继承的类的私有成员的打印方法。所以B会打印B私人成员和私人成员,C会打印C私人成员和私人成员,D会打印它的私人成员和B,私人成员。
在主函数中,我想为每个类的对象有3个位置的类A创建一个指针数组,然后我想循环每个对象的打印方法。
问题是当我将类更改为模板类时出现错误消息,说“我的类没有构造函数”;但是他们确实有他们。
这里是我的代码请帮助(注意我评论的地方发生的错误你):
#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;
}
}
在SO上发布时,尝试拿出仍然显示错误的最小示例,并提供确切的错误消息。你可能只需要A和B在这里产生错误,所以你可以减少一半的代码。 –
在'B类:公共A''你从什么'A'继承?由于'A'是一个模板,它的名字是不够的。 – NathanOliver
我觉得'所有这些都是模板课程'都是你所面临的误解的表现。他们是班级模板。这意味着如果你有'template class A'那么'A'本身不是一个类。只有你指定了所有的模板参数,它才会成为一个真正的类。所以'A '就是一个例子。 –
PeterT