C ++ ostream char **

时间:2014-08-23 19:31:48

标签: c++ ostream

我构建了一个班级Client,我希望得到ostream。这是班级:

class Client {
    MyString id;
    MyString full_name;
    char gender;
    unsigned short age;
    unsigned short hobbies_num;
    char** hobbies_list;

这是我已写过的代码片段:

ostream& operator<<(ostream& osc, const Client& for_print)
{
    return osc << for_print.id << endl << for_print.full_name << endl << for_print.gender << endl << for_print.age << endl << for_print.hobbies_num << endl;
}

我的问题是如何打印最后一个成员hobbies_list,这是一个二维动态的字符数组?

2 个答案:

答案 0 :(得分:0)

使用for循环。

for (int i = 0; i < for_print.hobbies_num; i++) {
    osc << for_print.hobbies_list[i] << endl;
}

答案 1 :(得分:0)

使用标准算法std::for_each

std::ostream& operator<<(std::ostream& osc, const Client& for_print)
{
    osc << for_print.id << endl << for_print.full_name << endl << for_print.gender << endl << for_print.age << endl << for_print.hobbies_num << endl;
    for_each(for_print.hobbies_list, for_print.hobbies_list + for_print.hobbies_num, [&](char* x){osc << x << endl; });
    return osc; 
}