A moments ago, I was exercising with design patterns, and recently, I've tried to implement a Factory Method pattern. My friend told me that I should always use smart pointers, so I've tried it, but my compiler throws an exception called "Access Violation". What am I doing wrong? There is one interface called "Shape", three inheriting classes from it, Client class and main function. I've tried to do everything with smart pointers, but I'm a little bit unsure, if I'm doing it right.
#include <iostream>
#include <memory>
class Shape
{
public:
virtual void printShape() = 0;
static std::shared_ptr<Shape> Create(int num);
};
class Triangle : public Shape
{
public:
virtual void printShape()
{
std::cout << "This is Triangle. \n";
}
};
class Circle : public Shape
{
public:
virtual void printShape()
{
std::cout << "This is Circle. \n";
}
};
class Rectangle : public Shape
{
public:
virtual void printShape()
{
std::cout << "This is Rectangle. \n";
}
};
class Client
{
private:
std::shared_ptr<Shape> shape;
public:
Client()
{
shape=Shape::Create(1);
}
std::shared_ptr<Shape>getShape()
{
return shape;
}
};
std::shared_ptr<Shape> Shape::Create(int num)
{
switch (num)
{
case 1:
return std::shared_ptr<Circle>();
break;
case 2:
return std::shared_ptr<Triangle>();
break;
case 3:
return std::shared_ptr<Rectangle>();
break;
}
}
int main()
{
std::shared_ptr<Client> client;
std::shared_ptr<Shape> shape = client->getShape();
shape->printShape();
}
Aucun commentaire:
Enregistrer un commentaire