zoukankan      html  css  js  c++  java
  • C++笔记012:C++对C的扩展——struct关键字类型增强

     


    原创笔记,转载请注明出处!

    点击【关注】,关注也是一种美德~


    C语言的struct定义了一组变量的集合,C编译器并不认为这是一种新的类型。

     

    C++中的struct是一个新类型的定义声明。

     

    struct Student

    {

    char name[100];

    int age;

    };

    void main()

    {

    Student s1={"wang",1};

    Student s2={"wang",2};

    }

     

     

    上面程序我们用.c文件,编译报错。

    这个时候c编译器不认为Student是一种新的类型,我们必须在Student前面加上struct关键字!

     

    struct Student

    {

    char name[100];

    int age;

    };

    void main()

    {

    struct Student s1={"wang",1};

    struct Student s2={"wang",2};

    }

     

     

    C++对struct关键字进行了功能增强。

    我们将同样的在c编译器下无法编译的程序放到.cpp文件中,发现是可以编译通过的!也就是说在C++中认为struct定义了一个新的类型,这个新的类型可以来定义新的变量。

     

     

    #include<iostream>

    using namespace std;

     

    struct Student

    {

    char name[100];

    int age;

    };

    void main()

    {

    Student s1={"wang",1};

    Student s2={"wang",2};

    system("pause");

    }

     

     

    另外呢,C++不单对struct关键字进行了类型增强,struct关键字和class关键字完成的功能是一样的,当然也有不一样的地方,区别后面再说。

    在结构体里面也可以加上访问数据权限:public、protected等。

     

     

    #include<iostream>

    using namespace std;

     

    struct Student

    {

    public:

    char name[100];

    int age;

    private:

    int a;

    };

    void main()

    {

    struct Student s1

    system("pause");

    }

     

     


    原创笔记,转载请注明出处!

    更多精彩请关注微信公众号:依法编程


     

     

  • 相关阅读:
    对C++虚函数、虚函数表的简单理解
    子数组最大累加和
    和为k的最长子数组及其延伸
    CentOS 安装codeblocks
    CentOS 6 安装chromium
    数组中累加和小于等于k的最长子数组
    数组最大矩形面积
    关于商品买卖最大收益的问题
    数组中只出现一次的数
    TinyHttpd代码解析
  • 原文地址:https://www.cnblogs.com/tyyhmtyyhm/p/8973877.html
Copyright © 2011-2022 走看看