2013-06-01 2 views
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() 함수를 어떻게 호출해야합니까?

답변

5

이 예상되는 동작입니까? 나에게 기대되는 출력을 얻으려면 Print() 함수를 어떻게 호출해야합니까?

예, 예상되는 동작입니다. 그들이 사본이 push_back()에 전달하는 객체의를 저장 :

문제

vector을 포함하여 표준 컨테이너는, 값 의미을 가지고있다. 한편, 다형성은 참조 의미 체계을 기반으로합니다. 올바르게 작동하려면 참조 또는 포인터가 필요합니다.

귀하의 경우에 발생하는 것은 CPolygon 개체가 sliced인데, 이는 원하는 것이 아닙니다. 문자 CPolygon 대신 포인터 (스마트 포인터)을 벡터에 저장해야합니다. 여기

#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; 
} 

live example입니다 :

이것은 당신이 당신 main() 기능을 재 작성하는 방법입니다.

+0

고마워요! 그것은 효과가 있었고 표준 포인터로 예제를 시도해 보았습니다. – mpestkow

+0

shared_ptr <>와 auto는 무엇입니까? [beginner] – Dineshkumar

+0

@Dineshkumar : 광범위한 주제입니다. StackOverflow에 새로운 질문을 던지십시오. (그러나 몇 가지 연구를하는 것을 잊지 마십시오. 첫째, 대답은 이미있을 수 있습니다) –