【问题标题】:Objects and Arrays [closed]对象和数组 [关闭]
【发布时间】:2020-01-15 16:54:07
【问题描述】:

如何创建对象数组并添加对象如下:

Student* student11 = new Student("Vince", "Vaughn", "7-th Avenue", "New York", "783-945-90-28", 49);
    Student* student12 = new Student("Vince", "Mcmahon", "Beverly Hills", "Los Angeles", "874-940-42-12", 47);
    Student* student13 = new Student("Stone Cold", "Steve Austin", "Dallas", "Texas", "385-421-47-95", 34);

【问题讨论】:

    标签: c++ arrays object initialization


    【解决方案1】:

    你的意思好像是下面这个

    Student *student = new Student[3] 
    {
        { "Vince", "Vaughn", "7-th Avenue", "New York", "783-945-90-28", 49 },
        { "Vince", "Mcmahon", "Beverly Hills", "Los Angeles", "874-940-42-12", 47 },
        { "Stone Cold", "Steve Austin", "Dallas", "Texas", "385-421-47-95", 34 }
    };
    

    如果Student 类没有默认构造函数,可能会出现问题,您需要重新分配数组。

    因此请注意,您可以使用标准模板类std::vector<Student>,而不是“手动”分配数组。

    【讨论】:

    • 是的,这是另一种方法,但如果您需要student4,您还需要手动使用realloc 以及:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2017-12-05
    • 2020-01-04
    相关资源
    最近更新 更多