• C和C++中的void*


    关于void*,今天同学提起,其实以前在《C++编程思想》中看过,内容是C语言中void*和其他

    类型的相互赋值都是可以的,但是C++中是不允许把void*赋值给其他类型的。做个代码试验如下:

     1 /* test.c  void*测试 */
     2 
     3  #include <stdio.h>  
     4  #include <stdlib.h>  
     5  
     6 
     7  typedef struct Test  
     8  {  
     9      int test;  
    10  } test;  
    11 
    12 int main() 
    13 { 
    14     test *ts = malloc(sizeof(test));  
    15 
    16     free(ts);    
    17 
    18     return 0; 
    19 }

    编译上述代码:

     wanpeng@ubuntu:~$ gcc test.c -o test

     wanpeng@ubuntu:~$ g++ test.c -o test

     test.c: In function ‘int main()’:test.c:11: error: invalid conversion from ‘void*’ to ‘test*’

    可以看到gcc编译没有错误,g++编译错误。

    ------------------------华丽的分割线----------------------------------------------------------

    对于以上情况的解释:

    因为C语言对于类型信息不挑剔,所以它允许这种事情。C++不同,类型在C++中是严格的,当类型

    信息有任何违例时就不允许。这一点对于C++尤其重要,因为在struct中有成员函数。如果能够在C++

    中向struct传递指针而不被阻止,那么我们就能调用struct逻辑上并不存在的成员函数。
    无类型包含有类型,比如无类型“车”,你可以说“轿车是车”,“卡车是车”,但是你不能说"车是轿车"或者"车是卡车"^_^

  • 相关阅读:
    二分搜素——(lower_bound and upper_bound)
    二分(搜索)查找
    算法复杂度中的O(logN)底数是多少
    hdu 1050 Moving Tables
    hdu 1010 Tempter of the Bone
    hud 3123 GCC
    “123”——> 123
    基本模运算
    101个MySQL的调节和优化的Tips
    一个最简单的图片缩略图
  • 原文地址:https://www.cnblogs.com/wanpengcoder/p/1789587.html
Copyright © 2020-2023  润新知