C++ what to code if i put a class after main() function

前端 未结 5 926
滥情空心
滥情空心 2020-12-30 17:26

I\'m watching some video tutorials on C++ and i know you must define a function / class before it is used or called. But I like having my main() function at the top, and eve

5条回答
  •  离开以前
    2020-12-30 17:59

    (note: all other answers are correct, but you may find this useful)

    I discovered this idiom to invert the order of main and secondary function classes. I use to share small code with colleagues, everybody expects the core of the code (i.e. main) to be on top so they can edit it quickly. It works with classes and functions (without need of declaration) of course. Usually I can leave the preamble (first #includes) because those have include guards in most cases.

    #include 
    using namespace std;
    
    #ifdef please_see_definitions_below_main
    int main()
    {
        ClassOne one;
        one.coolSaying();
        return 0;
    }
    #else
    class ClassOne
    {
        public:
            void coolSaying()
            {
                cout << "Cool stuff yo!" << endl;
            }
    };
    #define please_see_definitions_below_main
    #include __FILE__
    #endif
    

    I use the tag please_see_definitions_below_main so it serves as comment also, but if you don't like it you can use something shorter, like AFTER.

提交回复
热议问题