首先以一个类的定义作为例子
在名称为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; }