C++中结构体与类到底有什么区别

#include<iostream>
using namespace std;
typedef struct DemoS{
    private:
      char c;
      char x;
      int y;
    public:
    DemoS(){}
    DemoS(char c,char x,int y):c(c),x(x),y(y)
       {
           //cout<<this<<"有参构造"<<endl;
       }
      inline void setX(char x)
      {
           this->x=x;
      }
      inline void printX(){
          cout<<this->x<<endl;
      }
      ~DemoS()
      {
          //cout<<this<<"析构函数"<<endl;
      }

}DemoS;

class DemoC{
   private :
       char c;
       char x;
       int y;
   public:
       DemoC(){}
       DemoC(char c,char x,int y):c(c),x(x),y(y)
       {
           //cout<<this<<"有参构造"<<endl;
       }
       inline void setX(char x){
          this->x=x;
       }
       inline void printX()
       {
            cout<<this->x<<endl;
       }
       ~DemoC(){
         // cout<<this<<"析构函数"<<endl;
       }
};
int main(void)
{
    DemoC *c1= new DemoC('a','b',1);
    DemoC *c2=c1;
    cout<<"c1堆上的地址:"<<c1<<" c2堆上的地址:"<<c2<<endl;
    cout<<"c1指针地址:"<<&c1<<" c2指针地址:"<<&c2<<endl;
    DemoC c3= DemoC('a','b',1);
    DemoC c4=c3;
    cout<<"c3:"<<&c3<<" c4:"<<&c4<<endl;
    DemoC c5=DemoC('a','b',1);
    DemoC *c6=&c5;
    cout<<"c5:"<<&c5<<" c6:"<<c6<<endl;


    DemoS *s1=new DemoS('a','b',1);
    DemoS *s2=s1;
    cout<<"s1堆上的地址:"<<s1<<" s2堆上的地址:"<<s2<<endl;
    cout<<"s1指针地址:"<<&s1<<"  s2指针地址:"<<&s2<<endl;
    DemoS s3=DemoS('a','b',1);
    DemoS s4=s3;
     cout<<"s3:"<<&s3<<" s4:"<<&s4<<endl;
    DemoS s5=DemoS('a','b',1);
    DemoS *s6=&s5;

    cout<<"s5:"<<&s5<<" s6:"<<s6<<endl;

    return 0;

}

运行结果:

从上述代码可以看出Struct与Class好像根本没有区别,网上说类是引用类型,结构体是值类型,但是发现一个问题不管是结构体和类的实例化对象都可以随意存在堆上或者栈上,变量名和指针一定是存在栈上的,但是具体的内容存在堆或者栈就看具体操作,比如int* t=new int(1)这个简单的代码段,因为new返回的地址所以接受它的变量必须也是指针,指针内存地址存在的是栈上的,指向的内存地址是堆上的而且类也存在着字节对齐的问题并且Struct也有权限访问的设置(public private protected)和构造函数、析构函数。有个别不同点可能就是默认的访问权限的不一样,还有类的对象之间赋值是浅拷贝(需要注意内存的释放),结构体之间赋值是深度拷贝。

扫描二维码关注公众号,回复: 8872467 查看本文章
发布了26 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/m0_37920739/article/details/80807172