Friday, May 4, 2012

C++ MVC example

I'm calling this a MVC example for simplicity. It's actually separating 3 c++ files into 3 different responsibility for better organization and reuse-ability.

coordin.h
This is the header file which contain templates and functions prototype. This file will be included on the other 2 files.

#ifndef COORDIN_H_
#define COORDIN_H_

//structur templates
struct polar{
char from[50]; //distance from origin
char description[50]; //direction from origin
};

//prototype
int balls(polar test);

#endif


file2.cpp
This file contain functions called in file1.cpp
# include <iostream>
# include <cmath>
# include "coordin.h" //structure templates, function prototype, what links the scripts

//convert rectagular to polar coordinates
using namespace std;
int balls(polar test){
cout << test.description << endl << test.from << endl ;
}


file1.cpp
This file is where you put the meat of your program. This is where you bring all the previous files together.
#include <iostream>
#include "coordin.h" // structure templates, function prototypes. what links the scripts
using namespace std;

int main(){
polar test = {"mvc like","must compile both file1 and file2"};

balls(test);

return 0;
}


Now in order for this to work you must compile both file1.ccp and file2.cpp at the same time. Example:
$ g++ file1.cpp file2.cpp

No comments:

Post a Comment