[CPP] C++中类和结构体的区别

C++中结构体和类的区别

在C++中,结构体和类基本一致,除了小部分不同。主要的不同是在访问的安全性上。

  1. 在类中默认的访问权限是private,而结构体是public。
  2. 当从基类/结构体中派生时,类的默认派生方式是private,而结构体是public。

实例

#include <stdio.h> 

class Test { 
    int x; // x是private 
}; 
int main() 
{ 
  Test t; 
  t.x = 20; // 编译错误,因为x是私有的
  getchar(); 
  return 0; 
} 

// Program 2 
#include <stdio.h> 

struct Test { 
    int x; // x 是public 
}; 
int main() 
{ 
Test t; 
t.x = 20; // 编译正确 
getchar(); 
return 0; 
} 


// Program 3 
#include <stdio.h> 

class Base { 
public: 
    int x; 
}; 

class Derived : Base { }; //相当于是private派生

int main() 
{ 
Derived d; 
d.x = 20; //编译错误,因为是private派生来的 
getchar(); 
return 0; 
} 


// Program 4 
#include <stdio.h> 

class Base { 
public: 
    int x; 
}; 

struct Derived : Base { }; // 相当于是public派生

int main() 
{ 
Derived d; 
d.x = 20; // 编译正确
getchar(); 
return 0; 
} 

参考

https://www.geeksforgeeks.org/structure-vs-class-in-cpp/?ref=lbp

原文链接: https://www.cnblogs.com/WAoyu/p/13157664.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    [CPP] C++中类和结构体的区别

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/356670

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午11:20
下一篇 2023年3月2日 上午11:20

相关推荐