C++遍历结构体数组并赋值

main.cpp

#include 

using namespace std;

#include "student.h"

int main() {
    Student zhangsan = {"张三", 1001, man, 25};
    Student lisi = {"李四", 1002, wuman, 26};
    cout << zhangsan.name << "," << zhangsan.age << "," << zhangsan.num << "," << zhangsan.sex
         << endl;
    cout << lisi.name << "," << lisi.age << "," << lisi.num << "," << lisi.sex << endl;
    interMsg();
    getMsg();
    return 0;
}

student.cpp

//
// Created by Administrator on 2018/8/29.
//

#include 
#include 
#include "student.h"
#include "utils.cpp"

using namespace std;
#define random(x) (rand()%x)

Student students[100];

void interMsg() {
    size_t size = getArrayLen(students);
    cout << "size:" << size << endl;
//这种循环不能修改stu的num值
//    for (int i = 0; i 
//        Student item =students[i];
//        string &basic_string = item.getName();
//        const char *name = basic_string.c_str();
//        //cout << "item.name:" << name << endl;
//        size_t num = random(size);
//        cout << "item.num:" << num << endl;
//        item.num = num;
//    }
//使用指针接收 &students[i]即可
//    for (int i = 0; i 
//        Student *item = &students[i];
//        size_t num = random(size);
//        //下面这两种方式一样的
//        item->num = num;
//        (*item).num = num;
//    }
//这种最简单
//这个item 加上&就是去地址 即指针变量 *item即这个变量本身。
        for (auto &item : students) {
        size_t num = random(size);
        item.sex = man;
        cout << "item.num:" << num << endl;
        item.num = num;
    }
}

void getMsg() {
    for (auto item : students) {
        string &basic_string = item.getName();
        const char *name = basic_string.c_str();
        cout << item.name << "," << item.age << "," << item.num << "," << item.sex << endl;
    }
}

student.h

//
// Created by Administrator on 2018/8/29.
//

#ifndef CADDMORE_STUDENT_H
#define CADDMORE_STUDENT_H
using namespace std;

void interMsg();

void getMsg();

enum Sex {
    man = 1,
    wuman = 0
};

struct Student {
    string name;
    int num;
    Sex sex;
    int age;

    string &getName() {
        return name;
    }

    Sex getSex() const {
        return sex;
    }
};


#endif //CADDMORE_STUDENT_H

utils.cpp

//
// Created by Administrator on 2018/8/29.
//
#include 

using namespace std;

template<class T>
int getArrayLen(T &array)  /*使用模板定义一个函数getArrayLen,该函数将返回数组array的长度*/ {
    return (sizeof(array) / sizeof(array[0]));
}

总结:
1.for (auto &item : students) 中 &item为取指针,方便修改stu的参数。
2.utils.cpp为工具类,getArrayLen为C++通用的获取数组长度方法。
3.#define random(x) (rand()%x) 位宏定义 获取0~x范围内的随机数。
4.Sex枚举类型感觉比java简单。

你可能感兴趣的:(C++,Android,程序员学,C++)