注册 登录
编程论坛 C++教室

自定义string类中=赋值问题

MainRed 发布于 2009-11-13 19:06, 1612 次点击
mystring operator +(const mystring &str1, const mystring &str2)
{
    mystring mystr3;
....
    return mystr3;
}
mystring::mystring(const mystring &str2)//拷贝构造函数
{
    length = str2.length;
    str = new char [length + 1];
    strcpy(str,str2.str);
}
void mystring::operator =(const mystring &str2)
{
 .......
}
main函数中有s3 = s1 + s2;(mystring类型)
此语句先执行+,然后是拷贝构造函数,然后是=,但是其中在参数传值的过程我有些不明白,+ 完后返回的mystr3是拷贝构造函数参数的但是这时候mystr3应该是释放了啊,拷贝构造函数完了后的str也是传递给了=作参数.
我单步执行的.
赋值运算符系统默认的吗?什么时候应该自己重载.
 string null_book = "9-999-99999-9";
To create null_book, the compiler first creates a temporary by invoking the string constructor that takes a cstyle character string parameter. The compiler then uses the string copy constructor to initialize null_book as a copy of that temporary.
那用这里 = 干嘛用啊,vod string::operator =(const string & ) 应该是在这里赋值的吧.
思维混乱中.
3 回复
#2
qlc002009-11-13 22:16
string null_book = "9-999-99999-9";这里面得9-999-99999-9相当于是这个字符串赋值给null_book。(你定义的不是mystring吗?这个地方是不是定义的字符串啊)void string::operator =(const string & )这个函数是进行拷贝用的!直接作用于两个类对象。
#3
MainRed2009-11-14 12:15
对不起忘了说了
string null_book = "9-999-99999-9";
To create null_book, the compiler first creates a temporary by invoking the string constructor that takes a cstyle character string parameter. The compiler then uses the string copy constructor to initialize null_book as a copy of that temporary.
是我从C++primer拷贝的.
按上面说应该是tempstr=string("9-999-99999-9"),然后是(拷贝构造函数) null.string(tempstr)没用到 = 啊 .
#4
qlc002009-11-14 16:31
只要是两个对象的相等,以及在fun(string &)这样的函数都得调用拷贝构造函数的!
1