+ 1
Passing a function between files
I'm trying to pass a validate function from the main.cpp to a class file, Charecter.cpp . When I try this it says that the function was not defined in this scope. I could create the class all in the main.cpp all that, but I'm trying to organize the program and keep things unclutered. Any help?
5 Answers
+ 1
Well, first I don't know if it is just a typo but it should be #ifndef (why would you define something already defined?).
Then you have to verify that your files have this strucure:
//file_class.h
#ifndef CLASS_H_
#define CLASS_H_
#include <iostream>
using namespace std;
class MyClass{
private:
type attribute1;
type attribute2;
...
public:
type method1();
type method2();
...
};
#endif
-------------------------------------------------------------
//file_class.cpp
#include "file_class.h"
type MyClass::method1(){
//implementation
}
type MyClass::method2(){
//implementation
}
...
And in your main file you just need to include the header file.
Also I didn't write them but is always good to add a constructor and a destructor for your class.
0
can you give the details of which are your source and header files and what is in each one of them?
Best prectice is having a header with the definition and a source file with implementation, then you just include the .h in your main
0
Just the standard ones from the tutorial. created a class which made Character.h and Character.cpp.
main.cpp has #include "Character.h" and #include <iostream> at the moment, plan on adding more as needed.
Character.h has had nothing changed, so #ifdef CHARACTER_H and #define CHARACTER_H.
Character.cpp has #include "Character.h" and #Include <iostream>
0
//file_main.cpp
#include "file_class.h"
#include <iostream>
type Function(){
/*code*/
}
int Main(){
MyClass Example;
return 0;
}
----------------------------------------------------------------------------------------------------
//file_class.h
#ifndef CLASS_H_
#define CLASS_H_
#include <iostream>
using namespace std;
class MyClass{
private:
type attribute1;
type attribute2;
...
public:
MyClass();
type method1();
type method2();
...
};
#endif
----------------------------------------------------------------------------------------------------
//file_class.cpp
#include "file_class.h"
MyClass::MyClass(){
type Function(); //from the main file
...
}
----------------------------------------------------------------------------------------------------
The purpose I'm trying to get across is that I call a function that I'll be using throughout the entire program, not just inside a single class
0
Ok haha. Well... then you just have to add #include "main.cpp" in your file_class.cpp