如何返回“set”方法的子类类型
How to return subclass type for a `set` method?
我想有一个类,其中集合返回this
,所以我可以做嵌套集合。但是我的问题是,子类也会有一些集合,但如果API的用户首先从超类调用集合,类型改变,我不能调用子类方法。
class SuperA {
public:
SuperA* setValue(int x) {
return this;
}
}
class SubA : public SuperA {
public:
SubA* setOtherValue(int y) {
return this;
}
}
SubA* a = new SubA();
a->setValue(1)->setOtherValue(12); // Compile error
我该如何解决这个问题?由于
我觉得这听起来像是…奇怪的循环模板模式(CRTP)!
template <typename Child>
class SuperA
{
public:
Child* setValue(int x)
{
//...
return static_cast<Child*>(this);
}
};
class SubA : public SuperA<SubA>
{
public:
SubA* setOtherValue(int y)
{
//...
return this;
}
};
SubA* a = new SubA();
a->setValue(1)->setOtherValue(12); // Works!
搜索条件是协变返回类型。
你必须在子类中重新定义setValue
:例如
class SubA : public SuperA
{
public:
SubA *setValue(int x) { SuperA::setValue(x); return this; }
// other methods...
};
在这个例子中,setValue
是非虚拟的,SubA::setValue
隐藏了基类版本,它不覆盖。
如果函数是虚函数,那么只要子类版本的返回类型是指向超类版本返回类型的指针或引用,就仍然有效,并且会发生重写。
相关文章:
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将子类方法声明为基类的友元
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C ++类型特征:确保子类实现方法
- 函数从唯一代码调用正确的子类方法
- Arduino在子类中使用父类方法
- C++强制在子类中实现方法,但具有不同的签名
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 如何调用传递给 JNI 'jobject' 的 Java 对象的子类/子类的方法
- 将方法参数类型更改为子类中的派生类
- 如果指针的子类的方法对于子类是唯一的,如何访问这些方法?
- C++继承,如何在基类的方法中调用子类的方法?
- 在子类上调用模板化静态方法时获取类的类型名
- 检查子类是否执行了方法重写
- 将"this"从父类方法转换为子类方法是一种好的做法吗?
- 从C++中的父类实例访问子类方法
- 基类中的虚拟方法和子类中的非 Virtula 方法.仍然如何调用子类方法,即使它是非虚拟的
- C ,基础课程如何将子类作为成员包含并调用其方法