I have been working with java for awhile and because of my school projects I needed to switch C++. I tried to implement some patterns in C++ but unfortunately I couldn't. Specifically, I tried to implement abstract factory pattern but since I used separated files (habitual behavior from java:)) I got errors in compilation. Could you give me some tips about the compilation and modeling(if I should use .h files instead of .cpp files or not) of my code?
//run.cpp
#include <iostream>
usingnamespace std;
int main(){
HFact* fact;
#ifdef LINUX
HFact* fact = new HelloLinFact;
#elif WINDOWS
//HFact* fact = new HelloWinFact;
cout<<"At the moment this implementation is not valid..."<<endl;
#endif
CHello* hello = fact->getHelloNormal();
hello->say();
hello = fact->getHelloReversed();
hello->say();
hello = fact->getHelloWorld();
hello->say();
return 0;
}
//HFact.cpp
class HFact {
public:
externvirtual CHello* sayHelloNormal() = 0;
externvirtual CHello* sayHelloRev() = 0;
externvirtual CHello* sayHelloWorld() = 0;
};
//CHello.cpp
class CHello{
public:
virtualvoid say() = 0;
};
//HelloLinFact.cpp
class HelloLinFact : public HFact {
public:
CHello* getHelloNormal() {
returnnew HelloLinNormal;
}
CHello* getHelloReversed(){
returnnew HelloLinReversed;
}
CHello* getHelloWorld(){
returnnew HelloLinWorld;
}
};
//HelloLinNormal.cpp
#include <iostream>
class HelloLinNormal : public CHello(){
public:
void say(){
cout>>"HelloNormal class says: Hello!";
}
}
//HelloLinReversed.cpp
#include <iostream>
class HelloLinReversed : public CHello{
public:
void say(){
cout<<"HelloLinReversed says: olleH";
}
}
//HelloLinWorld.cpp
#include <iostream>
class HelloLinWorld : CHello{
public:
void say(){
cout<<"HelloLinWorld says: Hello World!";
}
}
I put all the classes in separate .cpp files. I will appreciate if you give me the compilation instructions for this code (I think I should link the object files to each other with gcc's -LObjName command but I couldn't do it). Additionally, any advice (putting classes to headers etc.) about the model is welcome.
And finally, module files typically follow this format:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <standard-stuff-needed-by-this-module-but-not-in-the-include-file>
...
#include "project-stuff-needed-by-this-module-but-not-in-the-include-file.hpp"
...
#include "my-include.hpp"
namespace my_include_hpp
{
// functions, etc. that are unique to this module
// (wrap it in a namespace to avoid linker name collisions with other libraries)
// definitions for everything declared in the hpp file
}
Finally, to compile everything together, there are several options. But in one shot it is: