C++的多態的被覆蓋的問題

來源:互聯網
上載者:User

      為了使用C++的多態性,需要儘可能的使用指標,而不是對象。C++在處理兩者的時候是不一致的。在進行函數傳遞時,基類有可能將繼承類的類型給掩蓋掉,從而喪失了多態。

class Base
{
public:
    virtual void print()
    {
        cout<<"Base "<<endl;
    }
};

class SubA: public Base
{
public:
    void print()
    {
        cout<<"SubA "<<endl;
    }
};

class SubB: public Base
{
public:
    void print()
    {
        cout<<"SubB\n";
    }
};

class Super
{
private:
    Base a1;//對象
    Base *a2;//指標
public:

    Super(Base &a,Base *b)
    {
        a1 = a;
        a2 = b;
    }

    void print1()
    {
        a1.print();
    }

    void print2()
    {
        a2->print();
    }
};


int main()
{
    Base b;
    SubA sa;
    SubB sb;

    Super s1(b,&b);
    s1.print1();
    s1.print2();

    Super s2(sa,&sb);
    s2.print1();
    s2.print2();

}

/**//*********************************
Base
Base
Base
SubB
*********************************/

上面結果可以看出

同是Base的子類,使用對象的類型被基類覆蓋掉了,而使用指標則沒有問題。

我認為是Super構造時,類的賦值造成的。

賦值和複製建構函式,經常會產生一些意想不到的副效應,而指標則不會。

在使用STL容器時,也盡量使用指標存放,除非是只對值感興趣。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.