小编use*_*923的帖子

继承函数返回派生类,而不是基类

是否可以在 C++ 中制定返回 Base 类型的 Base 类中的函数,以便在 Derived 类中,它们返回 Derived 类型,而无需重载?

最小的例子:

class Base
{
    public:
        Base(double v)
        {
            value = v;
        }

        Base add(Base b)
        {
            return Base(b.value + this->value);
        }

        void print()
        {
            std::cout << value << std::endl;
        }

        double value;
};



class Derived : public Base
{
    public:
        Derived(double v) : Base(v)
        {

        }

        void timesTwo()
        {
            value *= 2.0;
        }
};


int main()
{

    Derived d1(1), d2(2);

    // This doesn't work because the result is of …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance

5
推荐指数
1
解决办法
1647
查看次数

标签 统计

c++ ×1

inheritance ×1