cout 打印 volatile void* 为1问题

 

“volatile void* 的地址值cout却变成了1”这个问题。

这就要涉及到operator<<运算符重载的问题了。operator<<运算符的重载形式中,有对应const void*的,但是没有对应volatile void*的。同时我们知道,在C++的隐式转换中,不会移除const或者volatile限定。

我们通过查看文档§27.7.3.6.2  Arithmetic inserters [ostream.inserters.arithmetic]


operator<<(int _Val)
operator<<(basic_ostream<char, _Traits>& _Ostr, const char *_Val)
operator<<(const void *_Val)
char*类型的指针,不会被隐式转换为void*.

对于大多数的指针类型,iostream会将其隐式地转换为void * 以用于显示,但是不会对volatile型指针进行转换。正因为如此,C++默认将volatile指针转换为bool类型。
 

#include <stdio.h>
#include <iostream>
#include <math.h>

volatile void* gptr= NULL;
int main() {
    using namespace std;
    int a= 5;
    gptr =&a;
    cout << "我在编程中国学C++\n\n";
    printf("%d\n", (int) sizeof(gptr));
    printf("gptr 0: %#lx\n",(unsigned long) gptr);
    cout <<"gptr 1: "<< gptr<<endl;
    
    return 0;
}

结果:

我在编程中国学C++

8
gptr 0: 0x7ffc71251ee4
gptr 1: 1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值