四、结构体
C++中的结构体用法和C语言基本一致。不同点在于,C++的结构体可以写函数。
代码示例:
#include <iostream>
#include <stdio.h>
using namespace std;
struct Student
{
string name;
int age;
double score;
//c++中可以在结构体中直接编写函数
void study()
{
cout<<name<<"is studying"<<endl;
}
};
int main()
{
Student s1;
s1.study();
return 0;
}
运行结果:
is studying
五、指针和数组
C++中指针和数组的用法和C语言是一样的。在C++中,数组名可以被视为指向数组第一个元素的指针,因此可以像在C语言中一样使用指针来访问数组元素。另外,C++中也支持指针算术运算和指针的其他常见操作,这些和C语言中的操作类似。
代码示例:录入三个学生信息,并打印输出。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
struct student{
string name;
int age;
double score;
void study()
{
cout <<name<<"正在学习"<<endl;
}
};
int main()
{
const int SIZE = 3;
student s1[SIZE];//学生数组
student *ptr = s1;//指向学生结构体的指针
//录入学生信息
for(int i = 0;i < 3;i++)
{
cout<<"第"<<i+1<<"个学生姓名:";
cin>>ptr->name;
cout<<"第"<<i+1<<"个学生年龄:";
cin>>ptr->age;
cout<<"第"<<i+1<<"个学生成绩:";
cin>>ptr->score;
ptr++;
cout<<endl;
}
ptr = s1;
//打印学生信息
for(int i = 0;i < 3;i++)
{
cout<<"第"<<i+1<<"个学生姓名:"<<ptr->name<<endl;
cout<<"第"<<i+1<<"个学生年龄:"<<ptr->age<<endl;
cout<<"第"<<i+1<<"个学生成绩:"<<ptr->score<<endl;
ptr->study();
cout<<endl;
ptr++;
}
return 0;
}
运行结果:
第1个学生姓名:gaoyinjie
第1个学生年龄:17
第1个学生成绩:250
第2个学生姓名:gaoxiang
第2个学生年龄:18
第2个学生成绩:256
第3个学生姓名:xiaofeng
第3个学生年龄:25
第3个学生成绩:266
第1个学生姓名:gaoyinjie
第1个学生年龄:17
第1个学生成绩:250
gaoyinjie正在学习
第2个学生姓名:gaoxiang
第2个学生年龄:18
第2个学生成绩:256
gaoxiang正在学习
第3个学生姓名:xiaofeng
第3个学生年龄:25
第3个学生成绩:266
xiaofeng正在学习