printf和自定义类 [英] printf and custom class

查看:61
本文介绍了printf和自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自己的类,代表一个自定义字符串类.我正在使用VS2012RC.我已经重载了我的类CustomString的一些运算符.

I have my own class that represents a custom string class. I'm using VS2012RC. I have overloaded some operators of my class 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;
}

我可以定义我的对象并像这样使用它:

I can define my object and use it like 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());

没有任何错误.

但是如果我这样使用它:

But if i use it like this:

printf("%s\n", str);

msvcr110d.dll发生异常(内存访问错误)

There is an exception in msvcr110d.dll (error in memory access)

为什么 printf(str)可以,但是 printf(%s \ n",str)不能?

Why printf(str) is ok, but printf("%s\n",str) is not ok?

如何修改我的代码以使用 printf(%s \ n",str)?

How can i modify my code to use printf("%s\n",str) ?

...

经过数小时的谷歌搜索,我发现显式强制转换(string),static_cast(str)和_str()方法添加了一个以空字符结尾的字符:'\ 0';

After hours of googling, I found that explict cast (string), static_cast (str) and _str() method are add a null-terminated chars: '\0';

我已将我的代码修改为:

i've modified my code as:

printf("%s\n",str + '\0');

成功了!

有什么方法可以修改我的自定义构造函数,以添加一个以null终止的字符串,并以一个以null终止的char传递正确的值,以使以下代码起作用:

Is there any way to modify my custom constructor to add a null-terminated string and pass a correct value with null-terminated chars to get working the following code:

printf("%s\n",str);

推荐答案

您不能(至少不能以可移植的方式). printf 查看作为参数传递的对象,并将其视为%s ,它是一个char数组.您遇到未定义的行为.另外,传递给 printf 的参数可以说是无类型的.

You can't (at least not in a portable way). printf looks at the object passed as parameter and treats it as a %s, which is a char array. You run into undefined behavior. Also, the parameters passed to printf are, sort of say, type-less.

为什么printf(str)没问题?

Why printf(str) is ok?

因为第一个参数是类型,并且是 const char * .隐式强制转换是通过您的运算符进行的.其余参数的行为不同.

Because the first parameter is types, and is a const char*. The implicit cast is made via your operator. The rest of the parameters don't behave the same.

我会改用 cout ,并重载 operator<<(ostream& ;,常量CustomString&).

我说你不​​能,以一种便携的方式.对于像

I said you can't, in a portable way. For a class like

class CustomString
{
   char* str;
   //...
};

之所以可行,是因为类在内存中的表示方式.但是,这仍然是未定义的行为.

that might work, because of how classes are represented in memory. But, again, it's still undefined behavior.

这篇关于printf和自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆