Regarding C++ Include another class

前端 未结 5 1616
孤城傲影
孤城傲影 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条回答
  •  爱一瞬间的悲伤
    2020-12-04 18:58

    C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.

    Example

    ClassOne.hpp:

    class ClassOne
    {
    public:
      ClassOne(); // note, no function body        
      int method(); // no body here either
    private:
      int member;
    };
    

    ClassOne.cpp:

    #include "ClassOne.hpp"
    
    // implementation of constructor
    ClassOne::ClassOne()
     :member(0)
    {}
    
    // implementation of "method"
    int ClassOne::method()
    {
      return member++;
    }
    

    main.cpp:

    #include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler
    
    int main(int argc, char* argv[])
    {
      ClassOne c1;
      c1.method();
    
      return 0;
    }
    

提交回复
热议问题