I've been programming this app for quite a while now and have so many functions that I've been trying to avoid clustered together in one blob of code.
I'm relatively new to C and I think I understand header files and how to use them properly. But I've run into a slightly more complex problem that deals with private classes. Whenever I try to put these functions in different files and make headers for them I get a lot of errors. I want to keep the wxFrame class in the main.cpp file, but I also need the functions inside it to be defined outside of the file. I could really use some help.
main.cpp
class MyFrame : public wxFrame{
public:
MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
private:
void Carfunc();
void Busfunc1();
void Busfunc2();
void Busfunc3();
BusFunctions.cpp
void MyFrame::Busfunc1(){
// do stuff here
}
void MyFrame::Busfunc2(){
// do stuff here
}
void MyFrame::Busfunc3(){
// do stuff here
}
CarFunctions.cpp
void MyFrame::Carfunc(){
// do stuff here
}
CodePudding user response:
there are many ways you can do it. one is to have those methods (functions) to be defined in a Bus and a Car class.
then Busfunc1()
in MyFrame
for example can do return bus.func1()
Busfunc2()
in MyFrame
can do return bus.func2()
Carfunc()
in MyFrame
can do return car.func()
and so on...
or you can simply make the car and bus on MyFrame public. so that MyFrame has a car, and that car has the Carfunc() instead. and MyFrame has a bus too, and that bus has all the busfuncs instead of the MyFrame.
there is at least 4-5 other ways you can do it, including static methods, inheritance... they would all end up organizing your code in different files. it all depends on what you are trying to achieve. what is the real requirement? for sure, organizing code in general is always good, but what is Busfunc2? What is Carfunc anyway?
CodePudding user response:
DO NOT place the Class Declaration in main.cpp
when you do that CarFunctions.cpp
Don't know the class MyFrame
exist (same for BusFunctions.cpp) and the compiler will complain!
rather, I would suggest to stick to common conventions and:
create a header file named
MyFrame.hpp
for the declaration of classMyFrame
.create a single source file
MyFrame.cpp
and put all implementations there.
If you insist on splitting the same classe's implementations, then create something like
MyFrame_Car.cpp
andMyFrame_Bus.cpp
add
#include "MyFrame.hpp"
to any module that needsMyFrame
(MyFrame.cpp needs them too)link all the modules (cpp files) together.
// MyFrame.hpp
class MyFrame : public wxFrame{
public:
MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
private:
void Carfunc();
void Busfunc1();
void Busfunc2();
void Busfunc3();
...
...
}
// MyFrame_Bus.cpp
void MyFrame::Busfunc1(){
// do stuff here
}
void MyFrame::Busfunc2(){
// do stuff here
}
void MyFrame::Busfunc3(){
// do stuff here
}
// MyFrame_Car.cpp
void MyFrame::Carfunc(){
// do stuff here
}