hololive滚滚山免安装绿色中文版
995M · 2025-10-31
通过结构体创建变量的方式有三种,见下代码:
#include <iostream>
using namespace std;
struct Student {
    string name;
    int age;
    int score;
}s3;
int main() {
    // 创建方式一:创建空的然后赋值
    struct Student s1;
    s1.name = "John";
    s1.age = 18;
    s1.score = 10;
    cout << s1.name << " " << s1.age << " " << s1.score << endl;
    // 创建方式二
    struct  Student s2 = {"River", 18, 100 };
    // 创建方式三:定义结构体的时候顺手的事
    s3.name = "Jewel";
    s3.age = 18;
    s3.score = 10;
}
通过指针->来访问结构体的成员
#include <iostream>
using namespace std;
struct Student {
    string name;
    int age;
    int score;
}s3;
int main() {
    Student s = {"River", 20, 100};
    Student * p = &s;
    // 使用 -> 箭头来访问
    cout << p->name << " " << p->age << " " << p->score << endl;
}
结构体的成员可以是另一个结构体
#include <iostream>
using namespace std;
struct Student {
    string name;
    int age;
    int score;
};
struct Teacher {
    int id;
    string name;
    int age;
    Student student;
};
int main() {
    Teacher t;
    t.id = 2;
    t.name = "John";
    t.age = 10;
    t.student = {"River", 10, 20};
    return 0;
}
将结构体作为参数向函数中传递: 值传递 or 引用传递
#include <iostream>
using namespace std;
struct Student {
    string name;
    int age;
    int score;
};
// 值传递
void printStudent1(Student student) {
    student.age = 10; // 值传递:原来的对象值不变
    cout << student.name << student.age << student.score << endl;
}
// 地址传递
void printStudent2(Student * p) {
    p->age = 10; // 地址传递:原来的对象值会变
    cout << p->name << p->age << p->score << endl;
}
int main() {
    Student student = {"River", 10, 20};
    printStudent1(student);
    Student * p = &student;
    printStudent2(p);
    return 0;
}
作用:用 const 来防止误操作
#include <iostream>
using namespace std;
struct Student {
    string name;
    int age;
    int score;
};
// 地址传递
void printStudent2(const Student * p) {
    p->age = 10; // 报错,因为是 const,解决了引用误操作的问题
    cout << p->name << p->age << p->score << endl;
}
int main() {
    Student student = {"River", 10, 20};
    Student * p = &student;
    printStudent2(p);
    return 0;
}
 
                     
                            995M · 2025-10-31
 
                            90.9M · 2025-10-31
 
                            478M · 2025-10-31
