一 首先以一个类的定义作为例子
在名称为student.h的头文件中
#include <iostream> using namespace std; #include <string.h> class Student { public: //外部接口 void input(char* pid,char* pname,int a,float s); void modify(float s) {score=s;} //成员函数体放在类中自动成为内联函数 void display() ; private: //私有成员 char* id; char* name; int age; float score; };
在student.cpp中实student类的成员函数
#include "student.h" //包含类定义所在的头文件 void Student::input(char* pid,char* pname,int a,float s) { //成员函数的实现 id=new char[strlen(pid)+1]; strcpy(id,pid); name=new char[strlen(pname)+1]; strcpy(name,pname); age=a; score=s; } void Student::display() { cout<<" id:"<<id<<endl; //虽在类外,成员函数仍可访问私有成员 cout<<" name:"<<name<<endl; cout<<" age:"<<age<<endl; cout<<"score:"<<score<<endl; }
二 有关.h和.cpp文件的规范
https://www.cnblogs.com/mathyk/p/10921843.html
三 将类定义和实现分别放在两个不同的文件中,如student.h和student.cpp这样做的好处
1. 分开便于阅读,管理和维护
2. 将成员函数的实现放在类中和类外,在编译时含义是不一样的
3. 对软件开发商而言,他们可以向用户提供一些程序模块了接口,而 不公开程序的源代码
4. 将类定义放在头文件中,以后使用不必再定义,只需要一条包含头 文件命令即可,实现了代码重用。
5. 便于团队对大型软件的分工开发
原文链接: https://www.cnblogs.com/theda/p/11888367.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/306135
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!