c++primer plus 清单12.1,12.2 ,12.3 .

首先,
#include
#ifndef STRNGBAD_H_
#define STRNGBAD_H_
class Stringbad
{
private:
char*str;
int len;
static int num_string;
public:Stringbad(const char *s);
Stringbad();
Stringbad(const Stringbad&);
~Stringbad();
friend std::ostream&operator<<(std::ostream&os, const Stringbad &st);
Stringbad & operator=(const Stringbad&);
};

#endif
其次

#define _CRT_SECURE_NO_WARNINGS
#include “vector.h”
#include
int Stringbad::num_string = 0;
Stringbad::Stringbad(const char * s)
{
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
num_string++;
std::cout << num_string << “:”"<<str
<< "“object created \n”;

}

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

Stringbad::Stringbad(const Stringbad &st)
{
num_string++;
len =st.len;
str = new char[len+1];
std::strcpy(str, st.str);
std::cout << num_string << “:”" << str
<< “” object created\n";

}

Stringbad::~Stringbad()
{
std::cout << “”" << str << "“object delected,”;
–num_string;
std::cout << num_string << “left\n”;
delete[]str;
}

Stringbad & Stringbad::operator=(const Stringbad &st)
{
if (this == &st)
return *this;
delete[]str;
len = st.len;
str = new char[len + 1];
std::strcpy(str, st.str);
return *this;

// TODO: 在此处插入 return 语句

}

std::ostream & operator<<(std::ostream & os, const Stringbad & st)
{
os << st.str;
return os;
// TODO: 在此处插入 return 语句
}
最后
#include
using std::cout;
#include"vector.h"
void callme1(Stringbad&);
void callme2(Stringbad&);
int main()
{
using std::endl;
{
Stringbad headline1(“Celery stalks at midnight”);
Stringbad headline2(“letture 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 << “Initialize one object to another:” << endl;
Stringbad sailor = sports;
cout << “sailor:” << sailor << endl;
cout << “Assign one object to another :” << endl;
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 << “String passed by reference:\n”;
cout << " “”<<rsb<<""\n";
};
void callme2(Stringbad &sb)
{
cout << “String passed by value:\n”;
cout << " “” << sb << “”\n";
};
复制构造,赋值特别重要,要改写,不然用默认的就麻烦了,出错了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值