【c++】Usage Of Void(English)

本文深入探讨了C++中void类型的使用场景,包括无参数函数声明、无返回值函数定义以及void指针的应用。解析了void指针可以指向任何类型的数据,并详细解释了void指针的赋值、类型转换及使用限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
using namespace std;
//this program is about the usage of void in language C++
//[usage of void]
//1when func takes no arguments ,use void
//default_return_type func(void)
//2when func return no values, use void
//void func(parameters)
//[usage of void*]
//1.void* can point to any types of data, which means void* can be assigned
//by any types of data
int main(){
    char *p_char = new char[10];
    memset(p_char,'1',sizeof(p_char));
    void *p_void;
    p_void = p_char;
    char* p_char1 = (char*)p_void;
    cout << *p_char1;
//    cout << *(((char*)p_void)++); illegal
    return 0;
}

//2.when you wanna get the address storaged in the p_void, you should use casting methods like (int*)p_void
//3.void* is not a pointer-to-object type, which means that *p_void is illegal
//the reason is that void* only konw the starting address of the data in the me
//mory but void* don't know the size of the data, unless int(takes four bytes) or other self-defined
//class types  
//4.from 3 above we know that p_void += n is incorrect(no size of data is given)
//and ANSI think so, however GUN don't think so,they think that the void* should has the
//same size as char*(1 byte) for no reason

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值