我有一个类型Point,它只是以下的别名Vector3:using Point = Vector3;
我希望能够添加功能Point,但没有额外的状态。所以我想用继承自的类替换它Vector3:
class Point : public Vector3 {
using Base = Vector3;
using Base::Base;
Point(const Base& base) : Base(base) {}
Point(Base&&) : Base(std::move(base)) {}
Point& operator=(const Base& base) {
Base::operator=(base);
return *this;
}
Point& operator=(Base&& base) {
Base::operator(std::move(base));
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
这继承了基类构造函数,并允许转换/移动Vector3to的值Point,因为我们之前可以自由地这样做。
在此之前您可以做但无法使用此方法做的唯一事情是自由转换指针。 Point*->Vector3*仍然有效,但是Vector3*->Point*将不再隐式工作。
以这种方式替换 typedef 时是否还有其他极端情况?
编辑:到目前为止,我发现了一个问题,您无法转发声明类型别名,因此您可能让用户通过在标头中重新定义类型来解决该问题:typedef Vector3 Point这将因重构而中断。