c++ - 在 C++ 中,一个类是否可以有一个包含另一个类对象的数组?

标签 c++ oop object

例如,我有一个名为 Apple 的类和另一个名为 Basket 的类,我希望 Basket 类具有一个私有(private)属性,该属性是一个 Apple 对象数组。

我的代码:

篮子.h

#include <iostream>
#include <string>
#include <apple.h>

// defin basket
class Basket {
    //class attrs; private
    private:
        std::string name;
        // I want Basket objects to have an array of Apple objects
        // How do I do this?
        Apple [];
    public: //class function
        Basket(std::string); //constructor
        std::string get_name() {return (name);}
};

苹果.h

#include <iostream>
#include <string>

// defin apple
class Apple {
    //class attrs; private
    private:
        std::string name;
    public: //class function
        Apple(std::string); //constructor
        std::string get_name() {return (name);}
};

最佳答案

您可以这样做,这会在创建 Basket 实例时立即创建包含 50 个苹果的数组。如果你不想,你可以使用 std::vector<Apple> ,而是一个动态数组。

第一种方法:

class Basket {
    //class attrs; private
    private:
        std::string name;
        // I want Basket objects to have an array of Apple objects
        // How do I do this?
        Apple apples[50];
    public: //class function
        Basket(std::string); //constructor
        std::string get_name() {return (name);}
};

第二种方法:

 class Basket {
    //class attrs; private
    private:
        std::string name;
        // I want Basket objects to have an array of Apple objects
        // How do I do this?
        std::vector<Apple> apples;
    public: //class function
        Basket(std::string); //constructor
        std::string get_name() {return (name);}
};

如果您不确定如何使用vector类,可以查看this出。

关于c++ - 在 C++ 中,一个类是否可以有一个包含另一个类对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010403/

相关文章:

javascript - 在 JavaScript 中将对象的值分配给另一个数组

Angular 2 *ngFor 处理更新错误

c++ - 如何在 Linux ubuntu 中设置 C++ 环境变量?

c++ - 使用变量创建/初始化新对象

C++ std::regex 混淆

c++ - OpenCV 的 Python 或 C++ 编码之间的性能是否不同?

Javascript/Angular : Bind function to every object or make helper object?

C# 类变量的定义类型

VBA Excel GetObject 问题 - 运行时错误 91 - 未设置对象变量或 With block 变量

php - 使子类继承基类的现有实例