c++primer第十章课后编程题

#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这两个对象时相同的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值