C++Primer Plus 编程练习8.8,练习4,结构体引用和默认传参,及重载的实现

4下面是一个程序框架:
#include
using namespace std
#include // for strlen(),strcpy()
struct stringy
{
char* str;//points to a string
int ct
};//length of string(not counting ‘0’)

//prototypes for set(),show(),and show()go here
int main()
{
stringy beany;
char testing[l]] = “Reality isn’t what it used to be.”;

set(beany, testing);
//first argument is a reference
//allocates space to hold copy of testing,
//sets str member of beany to point to the
//new block,copies testing to new block,
//and sets ct member of beany
show(beany);
//prints member string once
show(beany,2);
//prints member string twice
testing[0] = 'D';
testing[1] = u';
	show(testing);
//prints testing string once
show(testing, 3);
//prints testing string thrice
show("Done!");
return 0;

}
请提供其中描述的函数和原型,从而完成该程序。注意,应有两个show()函数, 每个都使用默认参数。
请尽可能使用 cosnt 参数。set()使用 new分配足够的空间来存储指定的字符串。这里使用的技术与设计和
实现类时使用的相似。(可能还必须修改头文件的名称,删除 using编译指令,这取决于所用的编译器。)

#pragma region 练习4.cpp
/*
*/
#if 1
#include <iostream>
#include <cstring>		// for strlen(),strcpy()
using namespace std;
struct stringy
{
	char* str;		//points to a string
	int ct;			//length of string(not counting '0')
};
void set(stringy& stry, const char* ch);
void reset(stringy&);
void show(const char* sztxt, unsigned num = 1);
void show(const stringy& stry, unsigned num = 1);


//prototypes for set(),show(),and show()go here
int main()
{
	stringy beany;
	char testing[] = "Reality isn't what it used to be.";

	set(beany, testing);

	show(beany);
	show(beany,2);
	reset(beany);

	testing[0] = 'D';
	testing[1] = 'u';
	show(testing);
	show(testing, 3);
	show("Done!");
	return 0;
}
//赋值stringy结构的数据,使用之后要配合reset释放内存空间
void set(stringy& stry, const char* ch)
{
	stry.ct = (int)strlen(ch);
	stry.str = new char[stry.ct + 1];
	strcpy_s(stry.str,(rsize_t)stry.ct+1,ch);
}
//释放内存空间,和set,成对使用
void reset(stringy& stry)
{
	delete[]stry.str;
	stry.str = NULL;
}
//show方法1
void show(const char* sztxt, unsigned num)
{
	for (unsigned i = 0; i < num; i++)
	{
		cout << sztxt << endl;
	}
}
//show方法2
void show(const stringy& stry, unsigned num)
{
	for (unsigned i = 0; i < num; i++)
	{
		cout << stry.str << endl;
	}
}
#endif
#pragma endregion

这里主要的问题是,编写引用函数,和重构函数,重构函数当然也可以写成按时指针的形式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值