自己尝试写一个CString类,一个关于“+”操作符重载的问题
时间:2011-12-21
来源:互联网
我自己写了两个+运算符重载:
MyCString& operator+(const char* strAdd);
MyCString& operator+(const MyCString& strAdd);
但是如下测试时:
MyCString str1,str2;
str1 = "abc";
str2 = "123" + str1;
出现问题,意思就是说匹配不上
请问根据str2 = "123" + str1这句的一个+运算符重载如何定义?
作者: me5438 发布时间: 2011-12-21
CString 的字符操作很方便的。
有时可以: str2 = _T("123") + str1;
也最好用 str2.Format( _T("123%s"), str1 );
作者: keith_cheung 发布时间: 2011-12-21
为什么要重载啊?
CString 的字符操作很方便的。
有时可以: str2 = _T("123") + str1;
也最好用 str2.Format( _T("123%s"), str1 );
自己做测试学习呢
作者: me5438 发布时间: 2011-12-21
你应该再加几个友元函数类型的重载函数
作者: mayudong1 发布时间: 2011-12-21
定义为友元函数
作者: VisualEleven 发布时间: 2011-12-21
请问根据str2 = "123" + str1这句的一个+运算符重载如何定义?
定义为友元函数
这样?friend MyCString& operator+(const char *str,const MyCString &string);
作者: me5438 发布时间: 2011-12-21
MyCString& operator+(const MyCString& strAdd);
str1 = "abc";
str2 = "123" + str1;
怎么匹配的上。。。
"123"又不是你类的对象对它调用operator+(),肯定是不行。
str2 = str1 + "123";这样才和MyCString& operator+(const char* strAdd); 匹配
作者: modicum_ck 发布时间: 2011-12-21
String operator + (const String &s1,const String &s2)
这样可以避免6楼所说的情况。
如果不修改定义形式,则需要注意调用时常值字符串应该在“+”号的右侧。
作者: fight_in_dl 发布时间: 2011-12-21
MyCString& operator+(const char* strAdd, MyCString &strAdd2);
这样的话就只能返回strAdd2了;
作者: modicum_ck 发布时间: 2011-12-21
函数原型最好定义为如下形式:
String operator + (const String &s1,const String &s2)
这样可以避免6楼所说的情况。
如果不修改定义形式,则需要注意调用时常值字符串应该在“+”号的右侧。
请完全忽视掉8楼,SB了。。。
这些天没用c++都忘记了。
作者: modicum_ck 发布时间: 2011-12-21
MyCString& operator+(const char* strAdd);
MyCString& operator+(const MyCString& strAdd);
str1 = "abc";
str2 = "123" + str1;
怎么匹配的上。。。
"123"又不是你类的对象对它调用operator+(),肯定是不行。
str2 =……
嗯,是这样的,但是如果非要实现str2 = "123" + str1呢?毕竟"123" + str1的结果和str1 + “123”的值是不一样的呀
作者: me5438 发布时间: 2011-12-21
friend MyCString& operator+(MyCString &strAdd, const char* strAdd2);
两种形式都定义一下试试呗
作者: mayudong1 发布时间: 2011-12-21
MyCString& operator+(const char *str,MyCString& string)
{
char *pAdd = new char[strlen(str) + string.DataLen +1];
strcpy(pAdd,str);
strcat(pAdd,string.myData);
static MyCString stringAdd;
stringAdd = pAdd; //调用赋值运算符
delete pAdd;
return stringAdd;
}
一下是赋值“=”重载:
MyCString& MyCString::operator =(const char *str)
{
int nTagLen = strlen(str);
char* pAdd = new char[nTagLen+1];
if( pAdd )
{
strcpy(pAdd,str);
DataLen = nTagLen+1; //MyCString类表示长度成员
delete myData;
myData = pAdd; //MyCString类char*成员
}
return *this;
}
作者: lsq19871207 发布时间: 2011-12-21
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28