4
이 특정 코드 부분에 문제가 있습니다. 예상대로 가상 함수가 작동하지 않는 것 같습니다. 대신가상 함수 및 벡터 반복기
From CRectangle: Rectangle
From CTriangle: Triangle
내가 얻을 :
From CPolygon: Rectangle
From CPolygon: Triangle
이 예상되는 동작입니다
#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;
}
내가 할 전망? 나에게 기대되는 출력을 얻으려면 Print() 함수를 어떻게 호출해야합니까?
고마워요! 그것은 효과가 있었고 표준 포인터로 예제를 시도해 보았습니다. – mpestkow
shared_ptr <>와 auto는 무엇입니까? [beginner] – Dineshkumar
@Dineshkumar : 광범위한 주제입니다. StackOverflow에 새로운 질문을 던지십시오. (그러나 몇 가지 연구를하는 것을 잊지 마십시오. 첫째, 대답은 이미있을 수 있습니다) –