최근 pure abstract classes
에 static member functions
을 사용하여 파생 클래스의 개체에 대한 포인터를 초기화하는 예제를 발견했습니다. 디자인 패턴인지 또는 좋은 프로그래밍 실습인지 궁금합니다.순수 추상 클래스의 정적 멤버 함수에 관한 - 디자인 패턴?
class Shape;
typedef std::unique_ptr<Shape> shape_ptr;
class Shape{
public:
Shape(){};
virtual ~Shape(){};
virtual void draw() const = 0;
virtual float area() const = 0;
virtual shape_ptr clone() const = 0;
virtual shape_ptr create() const = 0;
static shape_ptr defineRectangle(int, int);
static shape_ptr defineCircle(float);
};
shape_ptr Shape::defineRectangle(int height, int width){
shape_ptr ptrRectangle = shape_ptr(new Rectangle(height, width));
return (ptrRectangle);
}
shape_ptr Shape::defineCircle(float radius){
shape_ptr ptrCircle = shape_ptr(new Circle(radius));
return (ptrCircle);
}
최종 목표 derived classes
의 컨테이너를 정의 할 수있다 : 다음의 코드 만 ilustration입니다 (예를 들어, defineRectangle() and defineCircle()
부재 기능 둘 다)이다. 예를 들어 :
std::vector<std::unique_ptr<Shape> > vect;
을 한 후 우리는에 의해 컨테이너에서 파생 된 클래스를 추가 할 수 있습니다 중 하나 Shape
클래스의 정적 멤버 함수 호출 : 어떤 인터페이스없이
vect.push_back(Shape::defineCircle(10));
vect.push_back(Shape::defineRectangle(5, 4));
직접 :
vect.push_back(std::unique_ptr<Shape>(new Circle(10)));
vect.push_back(std::unique_ptr<Shape>(new Rectangle(5,4)));
을
컨테이너에서 파생 클래스를 추가하는 두 가지 방법 중 어느 것이 우선되어야하며 그 이유는 무엇입니까?
전체 코드는 다음에서 찾을 수 있습니다. link.
어떤 조명도 정말 환영합니다 ;-)
,하지만 당신은 당신의'표준을 잊은 :: move' 's ... – kennytm