Ошибка LNK1120 с классами (шаблон Factory).Не уверен, откуда он - PullRequest
2 голосов
/ 08 февраля 2012

Извините, если я разместил слишком много кода. Я действительно не знаю, откуда исходит ошибка ссылки. Кажется, есть проблема с этой строкой:

dough = ingredientFactory->createDough();

в классе CheesePizza, но я не знаю, является ли ссылка componentFactory или проблемой в классе Dough. Может кто-нибудь сказать мне, почему он не будет ссылаться? (Я получаю ошибку LNK1120). Любая помощь будет принята с благодарностью.

Спасибо.

class Dough  
{
    string m_dough; 
public:
    Dough() : m_dough( "Unknown dough" ) {}; 
    string setDough( string dough ) { m_dough = dough; }; 
    string getDough() { return m_dough; }; 

};



class ThinCrustDough : public Dough 
{
public:
    ThinCrustDough() { setDough( "Thin crust dough" ); }; 
}; 


class PizzaIngredientFactory
{
 public:
    PizzaIngredientFactory() {}; 
    Dough *createDough();
    Sauce createSauce();
    Cheese *createCheese();
};



class NYPizzaIngredientFactory : public PizzaIngredientFactory
{
    Cheese *cheese; 
public: 
    NYPizzaIngredientFactory(){}; 
    Dough *createDough() { return new ThinCrustDough; };
    Sauce *createSauce() { return new MarinaraSauce; };
    Cheese *createCheese() { return new ReggianoCheese; };
}; 


 class Pizza
 {
    string m_size; 
    string m_description;
    string m_type; 

    PizzaIngredientFactory *ingredientFactory; 
    string m_name;
    string m_dough;
    string m_sauce;
    string m_cheese; 
    Dough dough; 
    Sauce sauce;
    Cheese cheese;

public:

    Pizza() : m_description("Unknown Pizza"), m_size(" ,Unknown Size ") {}; 
    Pizza( PizzaIngredientFactory *ingredientFactory ){ this->ingredientFactory = ingredientFactory; }; 

    string name() { return m_name; };
    string getName() { return m_name; }; 
    void setName( string name ) { m_name = name; };

    string getDescription() { return m_description; };
    string setDescription( string setdescription ) { return m_description = setdescription; }; 
    string getSize() { return m_size; };
    string setSize( string setsize ) { return m_size = setsize; };
    string getType() { return m_type; }; 
    string setType( string settype ) { return m_type = settype; };  
    virtual void prepare() = 0;
    void bake();
    void cut(); 
    void box(); 
    void orderPizza(); 

};


void Pizza::prepare()
{
    Pizza *pizza; 
    cout << "Preparing " << pizza->getName() << endl;
    cout << "Adding toppings : " << endl; 

    for ( vector<string>::iterator itr = toppings.begin();
           itr != toppings.end();
           ++itr )
    {
        cout << "    " <<  *itr;
    }

}; 



void Pizza::bake()
{
    cout << "Bake for 25 minutes at 350 degrees" << endl;
}; 



void Pizza::cut()
{
    cout << "Cutting the pizza into diagonal slices" << endl;
};



void Pizza::box()
{
    cout << "Place pizza in official PizzaStore box" << endl; 
};



class CheesePizza : public Pizza
{
    PizzaIngredientFactory *ingredientFactory;
    Pizza *pizza;
    Dough dough;
    Sauce *sauce; 
    Cheese *cheese; 

public:
    CheesePizza() { }; 
    CheesePizza( PizzaIngredientFactory *ingredientFactory ){ this->ingredientFactory = ingredientFactory; }; 
    void prepare(){

        cout << "Preparing " << getName() << endl; 

        dough = ingredientFactory->createDough();

    }; ; 

}; 




class PizzaStore 
{
    PizzaIngredientFactory *factory; 

public:
    PizzaStore() {}; 
    PizzaStore( PizzaIngredientFactory *factory ) { this->factory = factory; }; 
    Pizza *orderPizza( string type )
    {
        Pizza *pizza; 

        pizza = createPizza( type );  
        pizza->prepare(); 
        pizza->bake();
        pizza->cut();
        pizza->box();

        return pizza;
    }

protected:
    virtual Pizza *createPizza( string type ) = 0; 
}; 


class NYPizzaStore : public PizzaStore
{
    Pizza *pizza; 

public:
    NYPizzaStore() {}; 
    NYPizzaStore( Pizza *pizza ){ this->pizza = pizza; }; 

protected:
    Pizza *createPizza( string item )   
    {
        Pizza *pizza = NULL; 
        PizzaIngredientFactory *ingredientFactory = new NYPizzaIngredientFactory;

        string type = "New York Style"; 

        string cheese = "cheese"; 
        if ( strcmp( cheese.c_str(), item.c_str() ) == 0 ) 
        {
            pizza = new CheesePizza( ingredientFactory );
            pizza->setType( type + " Cheese Pizza" );
        }

        return pizza;
    }
 };

1 Ответ

1 голос
/ 08 февраля 2012

(Если я правильно помню, это происходит из Head First: шаблоны проектирования, c ++ - ized)Ваша проблема в том, что вы объявили некоторые функции в PizzaIngredientFactory , но не определили их, в результате чего компоновщик выдает сообщение об ошибке.Вы можете определить причину, посмотрев на ошибки.Компоновщик Visual Studio перечислит их в сообщении LNK2001 .Вы можете решить эту проблему, объявив эти функции виртуальными в PizzaIngredientFactory.Как предположил Йоахим Пилеборг, чистый виртуал предпочтительнее «простого» вируса, поскольку паттерн - это абстрактная фабрика.Следует также помнить, что классы, предназначенные для наследования, должны иметь виртуальный деструктор (но он также должен быть определен в базовом классе, в противном случае возникнет другая ошибка компоновщика).

...