#ifndef HEAD2_H_
#define HEAD2_H_
class Person
{
private:
static const int LIMIT=25;
std::string lname;
char fname[LIMIT];
public:
Person();
Person(const std::string &ln,const char *fn="Heyyou");
void Show() const;
void FormlShow() const;
};
#endif
#include <iostream>
#include <string>
#include "head2.h"
using namespace std;
Person::Person()
{lname="";fname[0]='\0';}
Person::Person(const std::string &ln, const char *fn)
{
lname=ln;
strcpy_s(fname,fn);
fname[25]='\0';
}
void Person::FormlShow() const
{
cout<<"lastname:"<<lname<<" firstname:"<<fname<<endl;
}
void Person::Show()const
{
cout<<"firstname:"<<fname<<" lastname:"<<lname<<endl;
}
#include<iostream>
#include<string>
#include"head2.h"
using namespace std;
int main()
{
Person one;
Person two("wang");
Person three("zhang","liu");
one.Show();
cout<<endl;
one.FormlShow();
cout<<endl;
two.Show();
cout<<endl;
two.FormlShow();
cout<<endl;
three.Show();
cout<<endl;
three.FormlShow();
cout<<endl;
system("pause");
return 0;
}
关于string型,我试过了,即使有using namespace std;string也会有或多或少的问题,例如这题,如果在头文件中没有用std::string,在定义成员变量的时候,构造函数重载会出问题,找不到重载的成员函数,所以,建议都用std::using。
另外,定义成员函数时,声明的时候有默认值,而在定义的时候,形参一定要把默认值去掉,只留数据类型,
关于赋值,fname是字符数组,而传递参数是指针,这时候不能直接赋值,要用strcpy函数,并将最后一个字符设置为结束字符。
#ifndef HEAD3_H_
#define HEAD3_H_
#include<iostream>
#include<string>
struct Golf
{
private:
std::string fullname;
int handicap;
public:
Golf(const std::string &fl="no name",int hc=0);
~Golf();
void showgolf();
Golf setgolf(std::string na="no name",const int ha=0);
};
#endif
#include<iostream>
#include<string>
#include"head3.h"
using namespace std;
Golf::Golf(const std::string & fl,int hc)
{
fullname=fl;
handicap=hc;
}
Golf::~Golf()
{
}
void Golf::showgolf()
{
cout<<"fullname:"<<fullname<<endl;
cout<<"handicap:"<<handicap<<endl;
}
Golf Golf::setgolf(std::string na,const int ha)
{
*this=Golf(na,ha);
return *this;
}
#include<iostream>
#include"head3.h"
#include<string>
using namespace std;
int main()
{
Golf one;
Golf two("wang");
Golf three("wang",2);
one.showgolf();
two.showgolf();
three.showgolf();
Golf four;
four=three.setgolf("liu",3);
three.showgolf();
four.showgolf();
system("pause");
return 0;
}
关于最后一个成员函数setgolf,返回的是this,也就是他本身,首先。*this=Golf(na,ha);构造函数先创建了一个临时的对象,其参数就是形参传递的值,这个临时对象又赋值给调用这个成员函数的对象,这就是后面main中three,因为是three调用的这个函数,这个函数又修改了调用它的对象,所以,最后的结果是three和four这两个对象时相同的。