C++中类的使用实例 (3中可能的构造函数调用)

类的定义头文件: 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




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值