sma*_*8dd 3 c++ inheritance casting return return-type
我有一个BaseClass,其方法返回一个类对象,我有一个DerivedClass.现在,当我有一个DerivedClass对象并调用BaseClass中定义的方法时,返回值是ob类型BaseClass,遗憾的是不是DerivedClass类型.
class BaseClass {
public:
typeof(*this) myMethod1() {return *this;} // nice if that would work
BaseClass& myMethod2() {return *this;}
BaseClass myMethod3() {return BaseClass();}
};
class DerivedClass : public BaseClass {};
DerivedClass tmp;
tmp.myMethod1();
tmp.myMethod2();
tmp.myMethod3();
// all three methods should return an object of type DerivedClass,
// but really they return an object of type BaseClass
Run Code Online (Sandbox Code Playgroud)
所以我希望实现的是使用超类的方法,但是使用派生类的返回类型(自动转换?).myMethod1()是我唯一能想到的,但它不起作用.
我搜索过但没有找到任何令人满意的东西.
您想使用CRTP(http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)模式:
template <class Derived>
class BaseClass {
public:
Derived *myMethod1() {return static_cast<Derived *>(this);}
Derived& myMethod2() {return static_cast<Derived&>(*this);}
};
class DerivedClass : public BaseClass<DerivedClass> {};
DerivedClass tmp;
tmp.myMethod1();
tmp.myMethod2();
Run Code Online (Sandbox Code Playgroud)