1.return一个struct对象的方法
例子:
转载:https://www.cnblogs.com/zplutor/archive/2011/09/25/2190315.html
struct S {
int Value;
};
S GetS(int value) {
S s;
s.Value = value;
return s;
}
int wmain() {
S s = GetS(10);
}
2.结构体作为函数的传入参数时
《1》值传递,形参发生任何改变,不改变实参的值
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
};
void print_(student s){
cout << s.name<<" " << s.age << endl;
s.name="李4";
}
int main(){
student s;
s.name = "lixiao";
s.age = 10;
print_(s);
cout << s.name<<" " << s.age << endl;
return 0;
}
运行结果:
《2》地址传递:形参改变后,实参跟着改变
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
};
void print_(student *s){
cout << s->name << " " << s->age << endl;
s->name = "李4";
}
int main(){
student s;
s.name = "lixiao";
s.age = 10;
print_(&s);
cout << s.name << " " << s.age << endl;
return 0;
}
在传入的结构体参数前加const 表示自函数体内部结构体参数不可修改。会报错
3. 结构体嵌套,输入,输出案例:
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct student
{
string name;
int sorce;
};
struct teacher
{
string name;
student student_[5];
};
void fuzhi(teacher Tarray[], int len_tea){
string str_ = "ABCDE";
srand((unsigned int)time(NULL));
for (int i_tea = 0; i_tea < len_tea;i_tea++)
{
Tarray[i_tea].name = "teacher_";
Tarray[i_tea].name += str_[i_tea];
int num_stu = sizeof(Tarray[i_tea].student_) / sizeof(Tarray[i_tea].student_[0]);
for (int i_stu = 0; i_stu < num_stu;i_stu++)
{
int random_ = rand() % 50+50;
Tarray[i_tea].student_[i_stu].name = "student_";
Tarray[i_tea].student_[i_stu].name += str_[i_stu];
Tarray[i_tea].student_[i_stu].sorce = random_;
}
}
}
void print_(teacher tarray[], int len){
for (int i_tea = 0; i_tea < len;i_tea++)
{
cout << "老师姓名: " << tarray[i_tea].name << endl;
int num_stu = sizeof(tarray[i_tea].student_) / sizeof(tarray[i_tea].student_[0]);
for (int i_stu = 0; i_stu < num_stu;i_stu++)
{
cout << "\t学生姓名:" << tarray[i_tea].student_[i_stu].name <<" "<<"成绩: "<<tarray[i_tea].student_[i_stu].sorce<< endl;
}
}
}
int main(){
teacher tea[3];
int len = sizeof(tea) / sizeof(tea[0]);
fuzhi(tea, len);
print_(tea, len);
return 0;
}