Regarding C++ Include another class

前端 未结 5 1614
孤城傲影
孤城傲影 2020-12-04 18:30

I have two files:

File1.cpp
File2.cpp

File1 is my main class which has the main method, File2.cpp has a class call ClassTwo and I want to c

5条回答
  •  Happy的楠姐
    2020-12-04 19:04

    The thing with compiling two .cpp files at the same time, it doesnt't mean they "know" about eachother. You will have to create a file, the "tells" your File1.cpp, there actually are functions and classes like ClassTwo. This file is called header-file and often doesn't include any executable code. (There are exception, e.g. for inline functions, but forget them at first) They serve a declarative need, just for telling, which functions are available.

    When you have your File2.cpp and include it into your File1.cpp, you see a small problem: There is the same code twice: One in the File1.cpp and one in it's origin, File2.cpp.

    Therefore you should create a header file, like File1.hpp or File1.h (other names are possible, but this is simply standard). It works like the following:

    //File1.cpp

    void SomeFunc(char c) //Definition aka Implementation
    {
    //do some stuff
    }
    

    //File1.hpp

    void SomeFunc(char c); //Declaration aka Prototype
    

    And for a matter of clean code you might add the following to the top of File1.cpp:

    #include "File1.hpp"
    

    And the following, surrounding File1.hpp's code:

    #ifndef FILE1.HPP_INCLUDED
    #define FILE1.HPP_INCLUDED
    //
    //All your declarative code
    //
    #endif
    

    This makes your header-file cleaner, regarding to duplicate code.

提交回复
热议问题