【发布时间】:2016-07-22 13:26:27
【问题描述】:
大家好,在我的 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;
}
}
【问题讨论】:
-
在 SO 上发帖时,尝试提出仍然显示错误的最小示例,并提供确切的错误消息。您可能只需要 A & B 即可在此处产生错误,因此您可以将代码减半。
-
在
class B:public AA你继承自什么?由于A是一个模板,它的名字是不够的。 -
我认为
All of them are template classes是您误解的症状。它们是类模板。这意味着如果您有template <typename Type> class A,那么A本身就不是一个类。只有在您指定了所有模板参数后,它才会成为一个实际的类。所以A<int>例如将是一个类。 -
好的,谢谢大家,下次我会确保让我的问题变小
标签: c++ oop pointers template-classes