标题:自定义string类中=赋值问题
取消只看楼主
MainRed
Rank: 1
等 级:等待验证会员
帖 子:7
专家分:0
注 册:2009-4-27
结帖率:0
已结贴  问题点数:20 回复次数:1 
自定义string类中=赋值问题
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 & ) 应该是在这里赋值的吧.
思维混乱中.
搜索更多相关主题的帖子: 赋值 定义 string 
2009-11-13 19:06
MainRed
Rank: 1
等 级:等待验证会员
帖 子:7
专家分:0
注 册:2009-4-27
得分:0 
对不起忘了说了
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)没用到 = 啊 .
2009-11-14 12:15



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-292208-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.240388 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved