学习C++多文件
如何制作一个c++的多文件代码呢?
我们来用刚才我所做到的一条简单的C++题目作为例子吧!
题目要求:用两个重载函数计算分别计算一个整数和一个字符串的长度。
我们打开VS2019进行操作:
上面是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;
}
这样,这个多文件就完成啦,可以运行了!