您的位置 电脑知识爱好者 >> 编程知识 >> C++函数设计, 函数发生器的设计

C++函数设计, 函数发生器的设计

电脑知识爱好者互联网电脑知识爱好者2008-5-1 5:36:29
知识重点:C++函数设计, 函数发生器的设计 (pass by pointer)。C++ 语言中多了引用传递(pass by reference)。由于引用传递的性质象指针传递,而使用方式却象值传递,初学者常常迷惑不解,容易引起混乱..
// 赋值函数

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;

参与评论
相关内容
关于我们 | 隐私政策 | 站点地图 | 站长博客|京ICP备07025396号
添加到百度搜藏 添加到百度搜藏 电脑知识爱好者Copyright ?2006-2008版权所有 我要啦免费统计