赞
踩
在C++中,struct
和class
都是用户定义类型(UDT)的关键字,用于封装数据和函数。尽管它们在许多方面都非常相似,但也存在一些关键差异。
struct
**:默认的成员访问权限是public
。class
**:默认的成员访问权限是private
。- struct StructExample {
- int data; // 默认为public
- };
-
- class ClassExample {
- int data; // 默认为private
- public:
- int getData() const { return data; }
- void setData(int d) { data = d; }
- };
在这个例子中,StructExample
中的data
成员默认是公开的,而ClassExample
中的data
成员默认是私有的。
struct
**:继承默认为public
。class
**:继承默认为private
。- struct BaseStruct {};
- struct DerivedStruct : BaseStruct {}; // 默认为public继承
-
- class BaseClass {};
- class DerivedClass : BaseClass {}; // 默认为private继承
这里DerivedStruct
公开继承BaseStruct
,而DerivedClass
私有继承BaseClass
。
struct
**:通常用于只有数据成员的简单数据结构。class
**:通常用于需要封装数据和函数的复杂数据结构。- struct Point {
- int x, y;
- };
-
- class Rectangle {
- Point topLeft, bottomRight;
- public:
- Rectangle(int x1, int y1, int x2, int y2)
- : topLeft{ x1, y1 }, bottomRight{ x2, y2 } {}
- int area() const {
- return (bottomRight.x - topLeft.x) * (bottomRight.y - topLeft.y);
- }
- };
Point
结构体仅包含数据成员,而Rectangle
类包含数据成员和函数,用于更复杂的操作。
两者都可以包含构造函数、析构函数和其他成员函数。
- struct StructWithFunctions {
- StructWithFunctions() { /* 构造函数实现 */ }
- ~StructWithFunctions() { /* 析构函数实现 */ }
- void function() { /* 成员函数实现 */ }
- };
-
- class ClassWithFunctions {
- public:
- ClassWithFunctions() { /* 构造函数实现 */ }
- ~ClassWithFunctions() { /* 析构函数实现 */ }
- void function() { /* 成员函数实现 */ }
- };
在这个例子中,StructWithFunctions
和ClassWithFunctions
都包含构造函数、析构函数和成员函数。
在C++中,struct
和class
是互换的,除了默认的访问权限和继承权限。你可以将struct
用于需要函数的场景,也可以在class
中只使用数据成员。
- class ClassAsStruct {
- public:
- int data; // 明确指定为public
- };
-
- struct StructAsClass {
- private:
- int data; // 明确指定为private
- public:
- int getData() const { return data; }
- void setData(int d) { data = d; }
- };
在这个例子中,ClassAsStruct
被用作只包含数据的结构体,而StructAsClass
则像一个类,封装了数据并提供了访问它的公共接口。
总之,struct
和class
在C++中提供了强大的数据封装功能。选择使用哪一个取决于你的设计需求,包括访问权限、继承和代码组织。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。