**
文件main.cpp 文件使用其他文件的函数(方法)
**
CLion(编辑工具) new 一个 c++ class 文件(Test)会生成两个文件(Test.h and Test.cpp)
.h 头文件
.cpp 源文件
- 头文件 Test.h
写类的声明(包括类里面的成员和方法的声明)、函数原型、#define常数等,但一般来说不写出具体的实现。
#ifndef CDEMO1_TEST_H
#define CDEMO1_TEST_H
class Test {
public: int dispaly();
private: int num=10;
};
#endif //CDEMO1_TEST_H
2.源文件 Test.cpp
源文件主要实现头文件中已经声明的那些函数的具体代码。需要注意的是,开头必须#include一下实现的头文件,以及要用到的头文件。那么当你需要用到自己写的头文件中的类时,只需要#include进来就行了。
#include<iostream>
#include "Test.h"
int Test::dispaly() {
num;
if (num>3){
return 56;
}
}
- main.cpp 文件调用Test.h 文件
#include <iostream>
#include <stdio.h>
#include "lbw.com.201911/24/Test.h"
using namespace std;
int main()
{
void testTest(Test test1); //声明 定义的函数
void demo_1_caLL_demo2(int s); //声明 定义的函数
cout << "Hello World" <<endl; // 输出 Hello World
Test test;
testTest(test);
demo_1_caLL_demo2(20); //使用 已经声明且定义过的函数
return 0;
}
void testTest(Test test1){
void testTestDispaly(int num1);
printf("%d\n",90);
if (test1.dispaly()>30){
testTestDispaly(test1.dispaly());
}
}
void testTestDispaly(int num1){
for(int s=num1;s < 60;s=s+1){
cout << "this s is " << s <<endl;
}
}
//方法 1 调用方法 2
void demo_1_caLL_demo2(int dm){
void demo_2(); //首先声明函数 下面调用
if (dm >10){
demo_2();
}
}
// 方法 2
void demo_2(){
//暑如果被调用输出
string str = "hello";
cout <<"outcome is ->>>"<<str <<endl;
}
本文详细介绍C++模块化编程的实践过程,包括如何在CLion中创建C++类文件,利用头文件和源文件分离的方法,实现函数的声明与定义。通过具体示例,展示如何在main.cpp文件中调用其他文件中的函数,实现代码的复用和管理。

被折叠的 条评论
为什么被折叠?



