[英]Use `operator const char*` in printf
struct MyClass
{
operator const char* ()
{
return "hello";
}
};
int main()
{
MyClass obj;
std::cout << obj; // ok
printf("%s\n", obj); // Crash
}
Why does object with operator const char*
can not be automatically converted to const char* string
in printf
for mapping the %s
? 为什么带有operator const char*
对象不能自动转换为printf
const char* string
来映射%s
?
Is it just because there is no type awareness in printf-like functions and %s
only expect a array of char with terminal 0? 是因为在类似printf的函数中没有类型感知, %s
只期望一个带有终端0的char数组?
Why? 为什么? Because of the limitations on variadic parameters in C++: they have essentially no type, you can think of them as void *
(but they're not). 由于C ++中可变参数的限制:它们基本上没有类型,你可以将它们视为void *
(但它们不是)。
So knowing that, the compiler has no idea you think that should be a string. 所以知道这一点,编译器不知道你认为应该是一个字符串。 It could very well need to be an integer, or a double, or another object. 它很可能需要是整数,双精度或其他对象。 Or just itself, which the compiler chooses. 或者仅仅是编译器选择的本身。
When you call printf
with: 当你用以下方法调用printf
时:
printf("%s\n", obj);
the compiler does not use the auto conversion function to convert obj
to char const*
. 编译器不使用自动转换函数将obj
转换为char const*
。 obj
is passed to printf
by value and printf
tries to treat that value as though it is char const*
. obj
按值传递给printf
, printf
尝试将该值视为char const*
。 As a consequence, your program exhibits undefined behavior. 因此,您的程序显示未定义的行为。 You'll have to explicitly cast obj
to char const*
to make your program behave predictably. 您必须显式地将obj
为char const*
以使您的程序可预测。
printf("%s\n", (char const*)obj);
If you turn on warning levels in your compiler, you'll probably see something to indicate that using obj
in that printf
call is not right. 如果在编译器中打开警告级别,您可能会看到一些内容表明在printf
调用中使用obj
是不对的。 With g++ -Wall
, I get: 使用g++ -Wall
,我得到:
socc.cc:16:23: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘MyClass’ [-Wformat=]
printf("%s\n", obj); // Crash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.