C++中 class 和 struct 的区别

C++中 class 和 struct 的区别


区别

在C++中,class 和 struct 的区别在于其默认的访问权限不同。
class  默认权限是 公共 public
struct 默认权限是 私有 private

代码如下(示例):

#include <iostream>

using namespace std;

class MyClass
{
    
    
	int my_age; //默认权限是 私有 private
};

struct MyStruct
{
    
    
	int my_age; //默认权限是 公共 public
};

void main()
{
    
    
	//class  and struct
	//class  默认权限是 公共 public
	//struct 默认权限是 私有 private
	MyClass C1;
	MyStruct S1;

	//C1.my_age = 18; 错误,访问权限是私有
	S1.my_age = 22;

	cout << S1.my_age << endl;

	system("pause");
}


总结

C++中,
class 默认权限是 公共 public
struct 默认权限是 私有 private

猜你喜欢

转载自blog.csdn.net/William_swl/article/details/128818942