C++Primer Plus对象和类的练习,练习10.10类和对象 练习3默认参数和重载

3.完成第9章的编程练习1,
连接查看细节
但要用正确的golf类声明替换那里的代码。
用带合适参数的构造函数替换 setgolf(golf&,const char*,int),以提供初始值。
保留 setgolf()的交互版本,但要用构造函数来实现它(
例如,setgolf()的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象即*this)。


class golf
{
public:
	golf(const char* name = "", int hc = 0);
	~golf();

	// interactive version:
	// function solicits name and handicap from user
	// and sets the members of g to the values entered
	// returns 1 if name is entered, 0 if name is empty string
	int setgolf(void);

	// function resets handicap to new value
	void sethandicap( int hc);

	// function displays contents of golf structure
	void showgolf(void)const;
private:
	static const int Len = 40;
	char fullname[Len];
	int handicap;
};

我们在这里添加析构函数,也希望和大家一起学习,了解真正的析构函数

#if 1
#include<iostream>
#include<cstring>
#include<string>
#include"golf.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::hex;
golf::golf(const char* name, int hc){
	int numCh = strlen(name) + 1;
	strcpy_s(fullname, numCh, name);
	handicap = hc;
}
int
golf::setgolf(void){
	cout << "输入名字:";
	string strname;
	getline(cin, strname);
	if ("" == strname){
		return 0;
	}
	cout << "输入差点:";
	int n;
	cin >> n;
	cin.get();
	if (!n) {
		return  0;
	}
	*this = golf(strname.c_str(), n);
}

void golf::sethandicap(int hc){
	handicap = hc;
}

void golf::showgolf(void)const{
	cout << fullname << "\t" << handicap;
}
golf::~golf(){
	cout << "Bye!\n";
	cout << hex;
	cout << "this address:" << this << endl;
}
#endif // 1

主函数执行

#pragma region 练习3
/*

*/
#if 1
#include <iostream>
#include"golf.h"
using namespace std;
int main()
{
	const unsigned num = 4;
	golf golfers[num];
	unsigned numGolfers = 0;
	while (numGolfers < num && golfers[numGolfers].setgolf()) {
		++numGolfers;
	}

	for (unsigned i = 0; i < numGolfers; i++)
	{
		golfers[i].showgolf();
		cout << endl;
	}

	cout << endl;
	return 0;
}
#endif 
#pragma endregion

看下有打印出来的效果,从这里可以看出this,指针的一个变化,和不变,临时变量的析构函数中打印出来的地址是一样的。
但是在申请的四个变量的this指针是
在这里插入图片描述

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值