虚函数和向量迭代器
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: %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;
}
下面是一个的实例
相关文章:
- 使用迭代器时如何访问对象在向量中的位置?
- 在 C++ 向量构造中包含迭代器
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- C++迭代器和向量
- 在无法访问向量的情况下查找迭代器的末尾
- C++ 向量插入和迭代器混淆
- 如何在C++中仅使用迭代器正确迭代 3D 向量?
- C++结构编译器错误询问向量的迭代器
- 为什么迭代器没有到达向量末端?
- 如何使用迭代器填充未知大小的向量?
- C++如何为向量向量构建迭代器
- 如何使用迭代器指向结构体c++的向量
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- 在C++中使用带有自定义向量的迭代器
- 使用条件迭代器插入到向量中
- 如何取消引用向量迭代器
- 如何从给定另一个迭代器向量的向量中删除元素
- 为什么迭代器向量::插入在填充后无效:迭代器插入(const_iterator位置,size_type n,常量value_type和val);
- C++ - 迭代器向量未编译的迭代器
- 对迭代器向量的重载<<