[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