类与结构体(1)

本文详细介绍了C++中结构体的基础概念,包括创建方法、成员访问方式(如通过`.`操作符),以及如何将结构体与容器如vector结合使用。后续将探讨结构体函数和析构函数的内容。
摘要由CSDN通过智能技术生成

讲题主要通俗易懂,略有不妥,还请见谅。(0基础也保证看得懂

结构体的基本概念

结构体(struct)顾名思义就是自己定的一个结构,例如常见的结构有:int , double, short, long long, flaot······对吧。这里的结构就是你自己的结构名。

我们先来看一下结构体的创建方法:

struct structname(随便你怎么取){
    type(int, double, long······) typename(自己发挥) 
    // 如果你想要在这里加一点函数也可以
};

我们暂定结构名是student,表示学生信息,这样好理解:

struct student{
    string name;
    int age;
};

没有问题吧!

那怎么访问呢?

#include <bits/stdc++.h>
using namespace std;
struct student{
	string s;
	int age;
};
int main()
{
	ios::sync_with_stdio(false),cin.tie(0);
	student Student; 
	cin >> Student.s >> Student.age;
	cout << Student.s << ' ' << Student.age;
    return 0;
}

你就把他当成 int 来用 int 后面要跟一个变量名对吧!那我们这个结构体后面也要跟一个名字

Studnet . s 是什么意思?' . ' 表示访问成员函数。  就是变量的意思 , 再想一下 string不是也有

string s ;  s . size();  这里size(),就是string 这个结构的成员函数。

懂了吗?

那换一种想法 int 后面是不是可以加 数组名,结构体也一样:
 

#include <bits/stdc++.h>
using namespace std;
struct student{
	string s;
	int age;
};
int main()
{
	ios::sync_with_stdio(false),cin.tie(0);
	int n;
	cin >> n;
	student Student[n];
	for(int i = 0; i < n; i++){
		cin >> Student[i].s >> Student[i].age;
		cout << Student[i].s << ' ' << Student[i].age << '\n';
	}
    return 0;
}

 我们懂了这个后,下一个讲student {} 后面那个分号干什么?

我们把刚刚那个代码换一种写法:

#include <bits/stdc++.h>
using namespace std;
int main()
{
	ios::sync_with_stdio(false),cin.tie(0);
	int n;
	cin >> n;
	struct student{
		string s;
		int age;
	}Student[n];
	for(int i = 0; i < n; i++){
		cin >> Student[i].s >> Student[i].age;
		cout << Student[i].s << ' ' << Student[i].age << '\n';
	}
    return 0;
}

在这个基础上我们再来讲一下结构体与容器的融合升华。

vector<int> 是不是对的, 那vector<student> 是不也是对的。

#include <bits/stdc++.h>
using namespace std;
int main()
{
	ios::sync_with_stdio(false),cin.tie(0);
	int n;
	cin >> n;
	struct student{
		string s;
		int age;
	};
	vector<student> Student(n);
	for(int i = 0; i < n; i++){
		cin >> Student[i].s >> Student[i].age;
		cout << Student[i].s << ' ' << Student[i].age << '\n';
	}
    return 0;
}

我们下期再见。

下期预告:

下次我们会讲结构体函数与结构函数,析构函数。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值