19.【c++基础篇.三个文件实现】

67 阅读1分钟

C++头文件、类实现文件、类的使用文件


在这里插入图片描述

(一)、为什么要使用多个文件进行编程?

如果一个类只被一个程序使用,那么累的声明和成员函数的定义可以直接写在程序的开头,但如果是一个类被多累程序使用,这样做重复的工作量就会很大了,效率也就低了.
在这里插入图片描述

(二)、三个文件的作用:

1.类声明头文件(后缀.h或则无后缀)

目的:是为了声明一个类的.

2.类实现文件(后缀为.cpp)

目的:是为了实现类的定义的.

3.类的使用文件(后缀为.cpp) 即主文件

目的是为了运行文件的.
在这里插入图片描述

(三)、使用基本注意事项:

在运用头文件的时候,要使用: #incldue “文件名.h”
在这里插入图片描述

(四)、实战项目.

1.代码展示:

头文件声明:

#pragma once
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
private:
	string name;
public:
	Student(string n);
	void show();

};

源文件定义:

#include <iostream>
#include "class.h"
using namespace std;
Student::Student(string n)
{
	name = n;
}
void Student::show()
{
	cout << "您的名字是:" << name;
}

主文件:

#include <iostream>
#include "class.h"
using namespace std;
int main()
{
	Student s("李明");
	s.show();


}

2.效果展示:

在这里插入图片描述