Clion
中使用头文件定义类,源文件实现
include什么
导入头文件(.h
)和源文件(.cpp
)
Note: 只导入 源文件(.cpp
) 也可以
CMakeLists.txt
1 2 3 4 5 6 7
| 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)
|
1 2 3 4 5 6 7
| # 遍历项目根目录下所有的 .cpp 文件 file (GLOB files *.cpp) foreach (file ${files}) string(REGEX REPLACE ".+/(.+)\\..*" "\\1" exe ${file}) add_executable (${exe} ${file}) message (\ \ \ \ --\ src/${exe}.cpp\ will\ be\ compiled\ to\ bin/${exe}) endforeach ()
|
代码
ElemType.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #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
|
ElemType.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #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; }
|
main.cpp
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream> #include "ElemType.h" #include "ElemType.cpp"
using namespace std;
int main() { ElemType e = ElemType(10); cout << e << endl; return 0; }
|
运算符重载:详见 运算符重载