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();
}