【发布时间】:2012-08-22 09:01:42
【问题描述】:
我有自己的代表自定义字符串类的类。我正在使用 VS2012RC。我已经重载了我的类 CustomString 的一些运算符。
这里有一些代码:
CustomString::CustomString(string setstr)
{
str = setstr;
}
CustomString::operator const char *()
{
return (this->str.c_str());
}
CustomString &CustomString::operator = (char *setstr)
{
str = setstr;
return *this;
}
我可以定义我的对象并像这样使用它:
CustomString str = "Test string";
我可以将结果打印为:
printf(str);
printf((string)(str).c_str());
printf((string)(str).data());
printf("%s\n",(string)(str).c_str());
printf("%s\n",(string)(str).data());
而且没有任何错误。
但如果我这样使用它:
printf("%s\n", str);
msvcr110d.dll中有异常(内存访问出错)
为什么printf(str)可以,printf("%s\n",str)不行?
如何修改我的代码以使用 printf("%s\n",str) ?
...
经过几个小时的谷歌搜索,我发现显式转换 (string)、static_cast (str) 和 _str() 方法都添加了一个以 null 结尾的字符:'\0';
我已将代码修改为:
printf("%s\n",str + '\0');
成功了!
有什么方法可以修改我的自定义构造函数以添加一个以空字符结尾的字符串并传递一个以空字符结尾的正确值以使以下代码正常工作:
printf("%s\n",str);
【问题讨论】:
-
您使用的修改完全靠运气。在 ... 中传递类对象会导致未定义的行为。
标签: c++ printing visual-studio-2012