程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Covariant Returen Types(協變返回類型),covariantreturen

Covariant Returen Types(協變返回類型),covariantreturen

編輯:C++入門知識

Covariant Returen Types(協變返回類型),covariantreturen


基類virtual func返回類型為某個類(class Super)的ptr或ref,子類重寫的virtual func返回類型可改為該類子類(class Sub : public Super)的ptr或ref。

                                               

class Base
{
public:
    virtual Base* clone() const { return new Base(*this); }
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    virtual Base* clone() const { return new Derived(*this); }
    virtual ~Derived() {}
};

int main()
{
    Derived d;
    Base* bPtr = d.clone();
    Derived* dPtr = dynamic_cast<Derived*>(bPtr);
    if(!dPtr) {
        delete dPtr;
        dPtr = nullptr;
        // throw exception ...
    }
    return 0;
}

改為:
......

class Derived : public Base
{
public:
    virtual Derived* clone() const { return new Derived(*this); }
    virtual ~Derived() {}
};

int main()
{
    Derived d;
    Derived* dPtr = d.clone();
    return 0;
}

                           

class Cherry {};

class BingCherry : public Cherry {};

class CherryTree
{
public:
    virtual Cherry* pick() const { return new Cherry(); }
};

class BingCherryTree : public CherryTree
{
public:
    virtual BingCherry* pick() const { return new BingCherry(); }
};

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved