簡體   English   中英

虛函數和向量迭代器

[英]Virtual functions and vector iterator

我在使用這段特定代碼時遇到了麻煩:虛擬函數似乎無法正常工作。

#include <cstdio>
#include <string>
#include <vector>

class CPolygon
{
protected:
    std::string name;
public:
    CPolygon()
    {
        this->name = "Polygon";
    }
    virtual void Print()
    {
        printf("From CPolygon: %s\n", this->name.c_str());
    }
};

class CRectangle: public CPolygon
{
public:
    CRectangle()
    {
        this->name = "Rectangle";
    }
    virtual void Print()
    {
        printf("From CRectangle: %s\n", this->name.c_str());
    }
};

class CTriangle: public CPolygon
{
public:
    CTriangle()
    {
        this->name = "Triangle";
    }
    virtual void Print()
    {
        printf("From CTriangle: %s\n", this->name.c_str());
    }
};

int main()
{
    CRectangle rect;
    CTriangle trgl;
    std::vector< CPolygon > polygons;
    polygons.push_back( rect );
    polygons.push_back( trgl );

    for (std::vector<CPolygon>::iterator it = polygons.begin() ; it != polygons.end(); ++it)
    {
        it->Print();
    }

    return 0;
}

我希望看到:

From CRectangle: Rectangle
From CTriangle: Triangle

相反,我得到:

From CPolygon: Rectangle
From CPolygon: Triangle

這是預期的行為嗎? 我該如何調用Print()函數來獲得我期望的輸出?

這是預期的行為嗎? 我該如何調用Print()函數來獲得我期望的輸出?

是的,這是預期的行為。

問題是標准容器(包括vector )具有值語義 :它們存儲傳遞給push_back()的對象的副本 另一方面,多態性基於引用語義 - 它需要引用或指針才能正常工作。

在你的情況下會發生的是你的CPolygon對象被切片 ,這不是你想要的。 您應該在向量中存儲指針 (可能是智能指針)而不是CPolygon類型的對象。

這是你應該重寫main()函數的方法:

#include <memory> // For std::shared_ptr

int main()
{
    std::vector< std::shared_ptr<CPolygon> > polygons;
    polygons.push_back( std::make_shared<CRectangle>() );
    polygons.push_back( std::make_shared<CTriangle>() );

    for (auto it = polygons.begin() ; it != polygons.end(); ++it)
    {
        (*it)->Print();
    }

    return 0;
}

這是一個實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM