c++ - How to implement Factory pattern? -


i trying implement factory class , interface. getting below error message. have created factory class decides class return normaltaxmanager or importedtaxmanager. have provided abstraction using interface.

#include<iostream> #include<vector> using namespace std;  class taxinterface { public:     virtual int calculate_tax(int price,int quantity)=0; };  class taxfactory { public:     // factory method     static taxinterface *callmanager(int imported)     {         if (imported == 0)             return new normaltaxmanager;         else             return new importedtaxmanager;     } };  class normaltaxmanager: public taxinterface { public:     virtual int calculate_tax(int price,int quantity)     {         cout << "normaltaxmanager\n";         price=quantity*price*10/100;         return price;     } };  class importedtaxmanager: public taxinterface { public:     virtual int calculate_tax(int price,int quantity)     {         cout << "importedtaxmanager\n";         price=quantity*price*5/100;         return price;     } };  int main() {     taxfactory f;     taxinterface *a = f.callmanager(1);     a->calculate_tax(100,2);     //    int price=taxinterface::callmanager(1)->calculate_tax(100,2); } 

problem:

 error: ‘normaltaxmanager’ not name type  error: ‘importedtaxmanager’ not name type 

you need declare normaltaxmanager , importedtaxmanager before taxinterface.

and need reverse.

in order fix (classical) c++ circular reference problem, need split code between .cpp , .h files

put taxinterface abstract , has no implementation in file of own : taxinterface.h.

for example, split importedtaxmanager in 2 files :

.h

#pragma once #include "taxinterface.h"  class importedtaxmanager : public taxinterface { public:     virtual int calculate_tax(int price, int quantity); }; 

.cpp

#include "stdafx.h" #include<iostream> using namespace std;   #include "importedtaxmanager.h"  int importedtaxmanager::calculate_tax(int price, int quantity) {     cout << "importedtaxmanager\n";     price = quantity*price * 5 / 100;     return price; } 

if re "clever" can "save" files.

but more easy maintain code split between headers (.h) , implementation (.cpp).

because c++ needs declarations of used, circular references can solved spliting between .h , .cpp

full working solution : http://1drv.ms/1pe25sq

regards


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -