(一)C++ 结构体的概叙
C++ 中结构体和类唯一的区别就是默认访问权限不同
- 类中成员的默认访问权限为:
private
(私有) - 结构体中成员的默认访问权限为:
public
(公共)
那么什么使用使用 类 什么是由使用 结构体?
一般定义数据节点时,使用结构体;而逻辑操作较多时,一般我们使用类。
(二)C++ 结构体的使用
(1)结构体的定义与变量声明
C++ 允许直接使用结构体名来定义变量,无需加上 struct
。
- 示例代码:
struct str
{
string name;
int num;
};
int main(int argc, char const *argv[])
{
str student;
student.name = "张三";
student.num = 1;
cout << "name: " << student.name << endl;
cout << "num: " << student.num << endl;
return 0;
}
/*
输出结果:
name: 张三
num: 1
*/
在 C语言中结构体不能封装函数,而在 C++ 中可以封装函数,使得结构体能像类一样来封装函数。
- 示例代码:
#include <iostream>
#include <string>
using namespace std;
struct str
{
string Name;
int Num;
// 定义结构体内函数
// 获取数据
void set_message(string name , int num)
{
Name = name;
Num = num;
}
// 输出数据
void show()
{
cout << "Name = " << Name << endl;
cout << "Num = " << Num << endl;
}
};
int main(int argc, char const *argv[])
{
str student;
student.set_message("张三" , 1);
student.show();
return 0;
}