C++文件与文件之间的函数调用以及 .h 和.cpp文件的创建用法与介绍

本文详细介绍C++模块化编程的实践过程,包括如何在CLion中创建C++类文件,利用头文件和源文件分离的方法,实现函数的声明与定义。通过具体示例,展示如何在main.cpp文件中调用其他文件中的函数,实现代码的复用和管理。

**

文件main.cpp 文件使用其他文件的函数(方法)

**

CLion(编辑工具) new 一个 c++ class 文件(Test)会生成两个文件(Test.h and Test.cpp)
.h 头文件
.cpp 源文件

  1. 头文件 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;
    }
}
  1. 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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值