C++中的new与struct

1.  从语法上,在C++中(只讨论C++中)。class和struct做类型定义时只有两点区别:
(一)默认继承权限。如果不明确指定,来自class的继承按照private继承处理,来自struct的继承按照public继承处理;

(二)成员的默认访问权限。class的成员默认是private权限,struct默认是public权限。

除了这两点,class和struct基本就是一个东西。语法上没有任何其它区别。

  2.使用new

有这样一个结构体:
typedef struct MineField 
{
BOOL isMine; //1 is mine,0 is not mine, -1 unknown.
int nearByNum; // the number of this grid's around.
MineField()
{
isMine = -1;
nearByNum = 0;
}
} MINEFIELD, *LPMINEFIELD;


MINEFIELD* pMineField;
pMineField = new MINEFIELD[count];
struct MineField*  s;
s= new MineField[10];

 

 

### C++ 中 `struct` 的使用方法和特点 #### 结构体定义初始化 在 C++ 中,`struct` 不仅能像 C 一样作为数据集合存在,还支持成员函数、访问控制符以及继承等面向对象编程特性。下面是一个简单的例子来展示如何定义并初始化一个结构体: ```cpp #include <string> struct Person { std::string name; int age; void introduce() const { std::cout << "My name is " << name << ", I am " << age << " years old." << std::endl; } }; int main(){ // 初始化方式一:直接赋值 Person person1{"Alice", 30}; // 初始化方式二:默认构造后设置属性 Person person2; person2.name = "Bob"; person2.age = 25; person1.introduce(); person2.introduce(); return 0; } ``` 此代码片段展示了两种不同的初始化方法,并且包含了成员函数用于打印个人信息[^1]。 #### 成员函数和支持的操作符重载 除了基本的数据存储外,C++ 还允许向 `struct` 添加行为——即成员函数。这使得它可以执行特定的任务或计算。此外,还可以实现操作符重载以便更自然地处理自定义类型的实例之间的交互。 ```cpp struct Point { double x, y; Point operator+(const Point& other) const{ return {this->x + other.x, this->y + other.y}; } bool operator==(const Point& other)const{ return (this->x == other.x && this->y == other.y); } }; Point p1{1.0, 2.0}, p2{3.0, 4.0}; auto sum_p = p1 + p2; // 使用加法运算符 bool equal = (p1 == p2); // 判断两个点是否相等 ``` 这段程序说明了怎样创建带有算术运算符(`+`)和比较运算符(`==`)的简单二维坐标类[^2]。 #### 继承机制 尽管通常认为只有 `class` 支持多态性和虚函数等功能,但实际上,在 C++ 中 `struct` 同样能够参单继承关系,默认情况下基类为公有(public),这意味着派生出来的子结构体会自动获得父级所有的公共接口。 ```cpp struct Shape { virtual double area() const = 0; // 抽象纯虚函数 }; struct Circle : public Shape { private: float radius_; public: explicit Circle(float r):radius_(r){} double area() const override final { return M_PI * pow(radius_, 2); } }; Shape* shape_ptr = new Circle(7.8f); std::cout<<shape_ptr->area()<<'\n'; // 输出圆面积 delete shape_ptr; ``` 上述案例构建了一个抽象图形基类及其具体圆形衍生版本,体现了基于 `struct` 实现继承的能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值