本文主要是介绍C++结构体嵌套,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include <iostream>
#include <string>
using namespace std;
//学生结构体
struct Student {
private:
string s_name;//学生姓名
public:
//构造函数
Student(string name) {
s_name = name;
}
//setter&getter
void setName(string name) {
s_name = name;
}
string getName() {
return s_name;
}
//自我介绍
void selfIntroduction() {
cout << "嗨,大家好,我是" << s_name << endl;
}
};
//老师结构体
struct Teacher {
private:
string t_name;//教师姓名
struct Student* m_stus;//教师指导的学生,这里用指针,如果是数组得指明长度,但是数组名不可变,不能set
int m_stus_size;//教师指导的学生的个数
public:
//构造函数
Teacher(string name, struct Student* stus, int stus_size) {
t_name = name;
m_stus = stus;
m_stus_size = stus_size;
}
//setter&getter
void setName(string name) {
t_name = name;
}
string getName() {
return t_name;
}
void setStus(struct Student stus[]) {//其实以指针形式接收
m_stus = stus;
}
Student* getStus() {
return m_stus;
}
void setStusSize(int stus_size) {//其实以指针形式接收
m_stus_size = stus_size;
}
int getStusSize() {
return m_stus_size;
}
//自我介绍
void selfIntroduction() {
cout << "大家好,我是" << t_name <<"老师,我带有"
<<m_stus_size<<"个学生,";
if (m_stus_size >= 2) {
cout << "分别是";
}
for (int i = 0; i < m_stus_size; i++) {
if (i == m_stus_size - 1) {
cout << m_stus[i].getName() <<",";
}
else if (i == m_stus_size - 2) {
cout << m_stus[i].getName() << "和";
}
else {
cout << m_stus[i].getName() << "、";
}
}
cout << "希望大家努力学习,不负韶华。" << endl;
}
};
int main() {
struct Student stus[] = {
{"张三"},
{"李四"},
{"王五"}
};
int len = sizeof(stus) / sizeof(stus[0]);
Teacher t = {"罗翔",stus,len};
t.selfIntroduction();
system("pause");
return 0;
}
这篇关于C++结构体嵌套的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!