为什么将字符指针流式传输到 cout 不打印地址?

2023-02-23C/C++开发问题
1

本文介绍了为什么将字符指针流式传输到 cout 不打印地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

当我使用 printf() 打印字符指针时,它会根据 %u 或 %s 使用转换说明符决定是打印地址还是整个字符串.

When I print a char pointer with printf(), it makes the decision with conversion specifier whether the address should be printed or the whole string according to %u or %s.

但是当我想用 cout 做同样的事情时,cout 将如何决定应该在地址和整个字符串中打印什么?这是一个示例源:

But when I want to do the same thing with cout, how will cout decide what should be printed among address and whole string? Here is an example source:

int main()
{
  char ch='a';
  char *cptr=&ch;
  cout<<cptr<<endl;
  return 0;
}

这里,在我的 GNU 编译器中,cout 试图将 ch 作为字符串输出.

Here, in my GNU compiler, cout is trying to output ch as a string.

如何使用cout通过cptr获取ch的地址?

How I can get address of ch via cptr using cout?

推荐答案

重载解析选择ostream&operator<<(ostream& o, const char *c); 用于打印 C 风格的字符串.你想要另一个 ostream&运算符<<(ostream& o, const void *p); 被选中.您可能最适合在这里使用演员表:

Overload resolution selects the ostream& operator<<(ostream& o, const char *c); which is used for printing C-style strings. You want the other ostream& operator<<(ostream& o, const void *p); to be selected. You are probably best off with a cast here:

 cout << static_cast<void *>(cptr) << endl;

这篇关于为什么将字符指针流式传输到 cout 不打印地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6