例如,我有一个名为 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/