着重C++编程规则,为找工作准备

class String
{?
// 赋值函数
String & operate=(const String &other);
// 相加函数,如果没有friend 修饰则只许有一个右侧参数
friend String operate+( const String &s1, const String &s2);
private:
char *m_data;
}
String 的赋值函数operate = 的实现如下:
String & String::operate=(const String &other)
{
if (this == &other)
return *this;
delete m_data;

m_data = new char[strlen(other.data)+1];
strcpy(m_data, other.data);
return *this; // 返回的是 *this 的引用,无需拷贝过程
}
对于赋值函数,应当用“引用传递”的方式返回String 对象。如果用“值传递”的
方式,虽然功能仍然正确,但由于return 语句要把 *this 拷贝到保存返回值的外部存
储单元之中,增加了不必要的开销,降低了赋值函数的效率。例如:
String a,b,c;
?
a = b; // 如果用“值传递”,将产生一次 *this 拷贝
a = b = c; // 如果用“值传递”,将产生两次 *this 拷贝

String 的相加函数operate + 的实现如下:
String operate+(const String &s1, const String &s2)
{
String temp;
delete temp.data; // temp.data 是仅含‘/0’的字符串
temp.data = new char[strlen(s1.data) + strlen(s2.data) +1];
strcpy(temp.data, s1.data);
strcat(temp.data, s2.data);
return temp;
}
对于相加函数,应当用“值传递”的方式返回String 对象。如果改用“引用传递”,
那么函数返回值是一个指向局部对象temp 的“引用”。由于temp 在函数结束时被自动
销毁,将导致返回的“引用”无效。例如:
c = a + b;
此时 a + b 并不返回期望值,c 什么也得不到,流下了隐患。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值