【发布时间】:2014-06-10 12:39:45
【问题描述】:
我有一个带有返回类对象的方法的 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
所以我希望实现的是使用超类的方法,但使用派生类的返回类型(自动转换?)。 myMethod1() 是我唯一能想到的,但它不起作用。
我已经搜索过,但没有找到任何令人满意的东西。
【问题讨论】:
标签: c++ inheritance casting return return-type