Clion中使用头文件和源文件坑

  • Clion 中使用头文件定义类,源文件实现

  1. include什么

    导入头文件(.h)和源文件(.cpp)
    Note: 只导入 源文件(.cpp) 也可以

  2. CMakeLists.txt

    1. 手动添加

      cmake_minimum_required(VERSION 3.15)
      project(HCpp)
      
      set(CMAKE_CXX_STANDARD 11)
      
      add_executable(HCpp main.cpp)
      add_executable(ElemType ElemType.cpp ElemType.h)
      
    2. 自动添加

      #if ($HEADER_COMMENTS)
      /**
      * Author: ${USER_NAME}
      * Date: ${DATE}
      * TODO: 
      * Describe: 
      #if ($ORGANIZATION_NAME && $ORGANIZATION_NAME != "")
      * Copyright (c) $YEAR ${ORGANIZATION_NAME}#if (!$ORGANIZATION_NAME.endsWith(".")).#end All rights reserved.
      #end
      */
      #end
      
  • 代码

  1. ElemType.h

    /**
     * Author: Dgimo
     * Date: 2020/4/1
     * TODO: 
     * Describe: 
     */
    
    #ifndef HCPP_ELEMTYPE_H
    #define HCPP_ELEMTYPE_H
    
    #include <iostream>
    
    class ElemType {
    public:
        int data;
    
        ElemType();
        ElemType(int);
        friend std::ostream &operator <<(std::ostream &, const ElemType &);
    };
    
    #endif //HCPP_ELEMTYPE_H
    
  2. ElemType.cpp

    /**
     * Author: Dgimo
     * Date: 2020/4/1
     * TODO: 
     * Describe: 
     */
    
    #include "ElemType.h"
    
    ElemType::ElemType() {
        this->data = 0;
    }
    
    ElemType::ElemType(int data) {
        this->data = data;
    }
    
    std::ostream& operator <<(std::ostream &out, const ElemType &e)
    {
        out << e.data;
        return out;
    }
    
  3. main.cpp

    #include <iostream>
    #include "ElemType.h"
    #include "ElemType.cpp"
    
    using  namespace std;
    

    int main() {
    ElemType e = ElemType(10);
    cout << e << endl;
    return 0;
    }

运算符重载:详见 [运算符重载

上一篇:顺序表


下一篇:栈的顺序存储结构