Person.h
#ifndef Person_H_ #define Person_H_ #include <string> using namespace std; class Person{ private: static const int LIMIT=25; string lname; char fname[LIMIT]; public: Person(){lname="default";fname[0]=' ';} Person(const string &ln,const char *fn="Heyyou"); ~Person(); void show()const; void FormalShow()const; }; #endif
Person.cpp
#include <iostream> #include "Person.h" #include <string> #include <cctype> using namespace std; /* Person::Person() { }*/ Person::Person(const string &ln,const char*fn)//不要写成const char*fn="Heyyou" { //会发生重定义参数错误 cout<<" ln address:"<<&ln<<endl; lname=ln; cout<<"lname address:"<<&lname<<endl; int i=0; for(;i<LIMIT&&fn[i]!=' ';i++) fname[i]=fn[i]; fname[i]=' '; } Person::~Person() {} void Person::show()const { cout<<" lname1:"<<lname<<endl; cout<<"lname address:"<<&lname<<endl; cout<<"fname1:"<<fname<<endl; //showChar(fname); } void Person::FormalShow()const { cout<<" lname address:"<<&lname<<endl; cout<<"fname2:"<<fname<<endl; cout<<"lname2:"<<lname<<endl; } void showChar(const char fn[]) { for(int i=0;fn[i]!=' ';i++) cout<<fn[i]; }
main102.cpp
#include <iostream> #include "Person.h" using namespace std; void main102() { Person p; p.show(); p.FormalShow(); Person p1("Smythe"); p1.show(); p1.FormalShow(); Person p2("Dimwiddy","Sam"); p2.show(); p2.FormalShow(); cin.get(); }