加号与等号运算符重载
class String
{…
// 赋值函数
String & operate=(const String &other);
// 相加函数,如果没有friend修饰则只许有一个右侧参数
friend String operate+( const String &s1, const String &s2);
private:
char *m_data;
}
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;
}
1 为什么返回temp的对象 ? 而不是temp的引用
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的引用,无需拷贝过程
}
这个例子作为 1的参考,为什么+重载符需要重新定义一个临时变量temp,而=重载符却直接用类的m_data ?
2 为什么不释放掉new出来的动态内存 ?
3 对于一个类的其中的一个数据成员new,该怎么delete?delete后 那不是对类不是动态分配的成员delete了。书上讲的都是基础数据类型malloc的实例 ,对类中不是动态分配的成员该怎么办? 那不是 把类的所有成员都删了 ?
分数不是重点,希望大家一起探讨探讨 求解答。