class 、struct和union的区别:

1.class 默认为私有熟悉,struct为公有属性

2.class 默认为私有继承,struct为共有继承

class base
{
   public:
     base(int a,int b)
       {
          this->a=a;
          this->b=b;
       }
     void print()
     {
         cout<<a<<b<<endl;
     }
    public: 
          int a;
          int b;
    private:
          int c;
          int d;
}

class child:public base//公有继承
{
    public:
         base(int a,int b,int c,int d):public base(a,b)
         {
            this->c=c;
             this->d=d;

         }
         void print_print()
         {
            cout<<a<<b<<c<<d<<e<<f<<endl;
         }
    public:
         int c,d;
    private:
         int e,f;
}


class child_1:base//公有继承
{
    public:
         base(int a,int b,int c,int d):public base(a,b)
         {
            this->c=c;
             this->d=d;

         }
         void print_print()
         {
            cout<<a<<b<<c<<d<<e<<f<<endl;
         }
    public:
         int c,d;
    private:
         int e,f;
}

int main()
{
    
    child c(1,2,3,4);
    c.a=2;
    c.b=3;
    child_1 c1;
    c1.a=2//错误,默认为私有继承,变成了私有属性。



}


3.union与struct的区别

       1.struct 的存储方式:

  

struct  demo
{
    int a;
    double b;
    short c;
};
struct demo1
{
    double a;
    int b;
    shorted c;
}

int main()
{
    demo d1;
    cout<<sizeof(d1)<<endl;
    demo d2;
    cout<<sizeof(d2)<<endl;
}

可以发现,struct的成员全部存在,且跟最大

的大小对齐。

#include <iostream>
using namespace std;
union myunion
{
	int a;
	double b;
	char c;
};
int main()
{
    myunion u;
	u.a=100;
	cout << sizeof(u) << endl;
	cout<<u.c<<endl;//c=d;00000000 00000000 00000000 01100100
    return 0;
}

 而union 在是所有的成员共同占据一块内存,每次赋值都会改变3个成员值,可以用来测量系统是大端还是小端。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值