C++ Primer Plus第六版编程练习10.3解答

Golf.h

#ifndef GOLF_H_INCLUDED
#define GOLF_H_INCLUDED

class Golf
{
private:
    static const int Len=40;
    char fullname[Len];
    int handicap;
public:
    Golf(char * fn="no name",int hc=0);
    ~Golf() {};
    int setGolf();
    void showGolf() const;
    void resetHandicap(int hc=0);
    char * returnFullname();
};

#endif // GOLF_H_INCLUDED

Golf.cpp

#include "Golf.h"
#include <iostream>
#include <cstring>  //for strcmp, strcpy

Golf::Golf(char * fn,int hc)
{
    strcpy(fullname,fn);
    handicap=hc;
}

int Golf::setGolf()
{
    std::cout<<"Please enter fullname and handicap:\n";
    char fn[Len];
    int hc;
    std::cin.getline(fn,Len);
    if(strcmp(fn,"")==0)  //当输入名字为空则结束
        return 0;
    std::cin>>hc;
    std::cin.get();
    *this=Golf(fn,hc);  //调用构造函数来创建一个临时对象,再把值赋给调用对象
    return 1;
}

void Golf::showGolf() const
{
    std::cout<<"fullname: "<<fullname<<std::endl;
    std::cout<<"handicap: "<<handicap<<std::endl;
    std::cout<<std::endl;
}

void Golf::resetHandicap(int hc)
{
    handicap=hc;
}

char * Golf::returnFullname()
{
    return fullname;
}

main.cpp

#include "Golf.h"
#include <iostream>
#include <cstring>

const int ArSize=4;

int main()
{
    using namespace std;

    Golf ann("Ann Birdfree",24);
    ann.showGolf();
    ann.resetHandicap(355);
    ann.showGolf();

    Golf team[ArSize];
    int i=0;
    while(i<ArSize && team[i].setGolf())
        i++;

    //输出team数组的内容
    cout<<endl;
    for(i=0; i<ArSize && strcmp(team[i].returnFullname(),"no name")!=0; i++)
        team[i].showGolf();

    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值