虚函数和向量迭代器

Virtual functions and vector iterator

本文关键字:迭代器 向量 函数      更新时间:2023-10-16

我对这段特定的代码有麻烦:虚函数似乎不像我期望的那样工作。

#include <cstdio>
#include <string>
#include <vector>
class CPolygon
{
protected:
    std::string name;
public:
    CPolygon()
    {
        this->name = "Polygon";
    }
    virtual void Print()
    {
        printf("From CPolygon: %sn", this->name.c_str());
    }
};
class CRectangle: public CPolygon
{
public:
    CRectangle()
    {
        this->name = "Rectangle";
    }
    virtual void Print()
    {
        printf("From CRectangle: %sn", this->name.c_str());
    }
};
class CTriangle: public CPolygon
{
public:
    CTriangle()
    {
        this->name = "Triangle";
    }
    virtual void Print()
    {
        printf("From CTriangle: %sn", 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对象得到切片,这不是你想要的。您应该在vector中存储指针(可能是智能指针),而不是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;
}

下面是一个的实例