我遇到了代码上的困难:
看起来虚函数并不按我预期那样工作。
我得到的是:
这是预期行为吗?我应该如何调用 Print() 函数来获得我期望的输出?
看起来虚函数并不按我预期那样工作。
#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() 函数来获得我期望的输出?