学习C++多文件

学习C++多文件

如何制作一个c++的多文件代码呢?
我们来用刚才我所做到的一条简单的C++题目作为例子吧!
题目要求:用两个重载函数计算分别计算一个整数和一个字符串的长度。
我们打开VS2019进行操作:
vs方案管理器
上面是VS2019的方案管理器,我们可以看见,我创建了一个头文件,名叫1.h(*.h是后缀)
然后我们在源文件里面创造了两个源文件来表示我们做多文件的决心(雾)。

如果不用多文件写代码,我想这道题目大家应该是这样写的:
#include<iostream>
using namespace std;
char count(char b[]);
int count(int a);
int main()
{
	int b;
	char a[30] = { 0 };
	cin.getline(a,30);
	cin >> b;
	count(a);
	cout << endl;
	count(b);
}

char count(char b[])
{
	int i = 0;
	while (b[i] != '\0')
	{
		i++;
	}cout << i ;
	return i;
}

int count(int a)
{
	int i = 1;
	while (a>=10)
	{
		a = a / 10;
		i++;
	}cout << i;
	return i;
}

不过今天我们玩点新的花样,我们用多文件来写:

1.如何写1.h这个头文件
//1.h
#include<iostream>
#include<cstring>
using namespace std;
int count(int a);
char count(char a[]);

//1.h的意思是注释,这个相当于写了一个新的头文件叫做1,然后我们后面可以用到它来作为头文件。
我们在1.h里面写了#include这样的头文件,方便以后的使用。

2.如何写cpp

我们定义了两个cpp,一个叫做m.cpp这个是用来作为主函数的存储cpp使用的,在这里,我们这样写:

//m.cpp
#include"1.h"
int main()
{
	int m;
	int a;
	cin >> a;
	char b[30] = { 0 };
	cin.getline(b, 30);
	m = count(a);
	cout << m << endl;
	m = count(b);
	cout << m;
}

接着,我们写了另一个cpp,我们取名为1.cpp,这个cpp我们用来声明函数:(当然这些随意你自由定制)

//1.cpp
#include"1.h"
int count(int a)
{
	int i = 1;
	while (a >= 10)
	{
		a = a / 10;
		i++;
	}
	return i;
}

char count(char a[])
{
	int i = 0;
	while (a[i]!='\0')
	{
		i++;
	}
	return i;
}

这样,这个多文件就完成啦,可以运行了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值