C++继承的模板类&初始化列表
我一直在将一些数学类转换为模板并使用初始化列表,当继承的类需要在初始化时访问基类数据成员时,就会遇到问题。
代码如下:
template <typename T>
struct xCoord2
{
T x;
T y;
xCoord2(T _x, T _y) : x(_x), y(_y) {};
};
template <typename T>
struct xCoord3 : xCoord2<T>
{
typedef xCoord2<T> B;
T z;
// All Error
xCoord3(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {};
xCoord3(T _x, T _y, T _z) : B::x(_x), B::y(_y), z(_z) {};
xCoord3(T _x, T _y, T _z) : this->x(_x), this->y(_y), z(_z) {};
// Works
xCoord3(T _x, T _y, T _z) { B::x = 0; B::y = 0; z = 0; };
};
是否可以在继承的类上使用初始化列表?
I have been converting some of my math classes to templates and to use initialization lists, and run into a problem when the inherited class needs to access base class data members on initialization.
Here is the code:
template <typename T>
struct xCoord2
{
T x;
T y;
xCoord2(T _x, T _y) : x(_x), y(_y) {};
};
template <typename T>
struct xCoord3 : xCoord2<T>
{
typedef xCoord2<T> B;
T z;
// All Error
xCoord3(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {};
xCoord3(T _x, T _y, T _z) : B::x(_x), B::y(_y), z(_z) {};
xCoord3(T _x, T _y, T _z) : this->x(_x), this->y(_y), z(_z) {};
// Works
xCoord3(T _x, T _y, T _z) { B::x = 0; B::y = 0; z = 0; };
};
Is it possible to use initialization lists on inherited classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要调用基类构造函数:
如果这些是非模板类,则没有什么不同:您只能在派生类构造函数中初始化派生类的基类和成员变量。
You need to invoke the base class constructor:
This would be no different if these were nontemplate classes: you can only initialize the base classes and member variables of the derived class in the derived class constructor.