类的定义头文件: Person.h
#ifndef Person_h
#define Person_h
#include <string>
using std::string; // string 类必须包含进去。
class Person
{
private:
static const int LIMIT=25;
string lname;
char fname[LIMIT];
public:
Person();
Person(const string & ln,const char * fn="heyyou");
// 第二个参数是在定义时初始化了,如果在具体函数实现时没有给定第二个参数,则就是这个默认初始化值。
void Show() const;
void Formalshow() const;
};
#endif
类的实现文件: clss.cpp
#include <iostream>
#include "Person.h"
using namespace std;
//默认构造函数
Person::Person()
{
lname=" ";
fname[0]= '\0';
}
//自定义构造函数,没有返回类型。注意:第二个参数不能和头文件中定义的一样将fn初始化。
Person::Person(const string & ln,const char * fn)
{
lname=ln;
strncpy(fname,fn,LIMIT-1);
fname[LIMIT]='\0';
}
void Person::Show()const
{
cout<<"Person's first name is:"<<fname<<",last name is:"<<lname<<endl;
}
void Person::Formalshow()const
{
cout<<"Person's last name is:"<<lname<<",first name is:"<<fname<<endl;
}
客户使用文件 use.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
Person one;
Person two("wengping");
Person three("wengping","sam");
//三种可能的构造函数调用。因为自定义构造函数中,第二个参数在声明时已经初始化了。
one.Show();
one.Formalshow();
cout<<endl;
two.Show();
two.Formalshow();
cout<<endl;
three.Show();
three.Formalshow();
cout<<endl;
return 0;
}
linux下编译:
g++ -o class.exe clss.cpp use.cpp
结果:
Person's first name is:,last name is:
Person's last name is: ,first name is:
Person's first name is:heyyou,last name is:wengping
Person's last name is:wengping,first name is:heyyou
Person's first name is:sam,last name is:wengping
Person's last name is:wengping,first name is:sam