cpp 12.1

strngbad.h

#pragma once
#include<iostream>

class StringBad
{
private:
	char*str;
	int len;
	static int num_strings;
public:
	StringBad(const char*s);
	StringBad();
	~StringBad();

	friend std::ostream & operator<<(std::ostream & os,
		const StringBad & st);
};

strngbad.cpp

#include<cstring>

#include"strngbad.h"
using std::cout;

int StringBad::num_strings = 0;

StringBad::StringBad(const char*s)
{
	len = std::strlen(s);
	str = new char[len + 1];
	std::strcpy(str, s);
	num_strings++;
	cout << num_strings << ":\"" << str
		<< "\"object created\n";
}

StringBad::StringBad()
{
	len = 4;
	str = new char[4];
	std::strcpy(str, "c++");
	num_strings++;
	cout << num_strings << ":\"" << str
		<< "\"default object created\n";
}

StringBad::~StringBad()
{
	cout << "\"" << str << "\"object deleted, ";
	--num_strings;
	cout << num_strings << " left\n";
	delete[] str;
}

std::ostream & operator<<(std::ostream & os, const StringBad & st)
{
	os << st.str;
	return os;
}

vegnews.cpp

#include<iostream>
using std::cout;
#include"strngbad.h"

void callmel(StringBad &);
void callme2(StringBad);

int main()
{
	using std::endl;
	{
		cout << "Starting an inner block.\n";
		StringBad headline1("Celery Stalks at Midnight");
		StringBad headline2("Lettuce Prey");
		StringBad sports("Spinash Leaves Bowl for Dollars");

		cout << "headline1: " << headline1 << endl;
		cout << "headline2: " << headline2 << endl;
		cout << "sports: " << sports << endl;

		callme1(headline1);
		cout << "headline1: " << headline1 << endl;
		callme2(headline2);
		cout << "headline2: " << headline2 << endl;

		cout << "Initalize one object to another:\n";
		StringBad sailor = sports;
		cout << "sailor: " << sailor << endl;
		cout << "Asssign one object to another:\n";
		StringBad knot;
		knot = headline1;

		cout << "knot: " << knot << endl;
		cout << "Exiting the block.\n";

	}

	cout << "End of main()\n";

	system("pause");
	return 0;
}

void callme1(StringBad & rsb)
{
	cout << "StringBad passed by reference:\n";
	cout << "  \"" << rsb << "\"\n";
}

void callme2(StringBad sb)
{
	cout << "String passed by value:\n";
	cout << "  \""<<sb<<"\"\n";
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值