简体   繁体   English

了解指向 c++ 中 object 的指针数组

[英]Understanding an array of pointers to an object in c++

There are 3 types of planes.有3种类型的飞机。

  • A nA321 which has a max capacity of 10 containers最大容量为 10 个容器的 nA321
  • nB777 which has a max capacity of 32 containers nB777 最大容量为 32 个集装箱
  • nB787 which has a max capacity of 40 containers nB787 最大容量为 40 个集装箱

I want to index through the list and create an Airplane object and store the respective value.我想对列表进行索引并创建一个 Airplane object 并存储相应的值。 My for loop will create a new Airplane object that is set to 10. How can I dynamically set the respective plane types to the corresponding max capacity?我的 for 循环将创建一个新的 Airplane object 并设置为 10。我如何动态地将各个飞机类型设置为相应的最大容量? The code currently outputs the address, for example:代码目前输出地址,例如:

Airplane 1 maximum load 0xffe飞机 1 最大载荷 0xffe

I am trying to print the following:我正在尝试打印以下内容:

Airplane 1 maximum load 10
Airplane 2 maximum load 10
Airplane 3 maximum load 10
Airplane 4 maximum load 10
Airplane 5 maximum load 32
Airplane 6 maximum load 32
Airplane 7 maximum load 40

My code我的代码

#include <iostream>

using namespace std;

class Airplane
{
    public:
        Airplane(int n); // the maximum capacity of the airplane
        int maxLoad(void) const;
        int currentLoad(void) const;
        bool addContainers(int n);
    private:
        const int maxContainers;
        int numContainers;
};

Airplane::Airplane(int n):maxContainers(n){
    n = maxContainers;
}

int Airplane::maxLoad(void) const{
    return maxContainers;
}

int Airplane::currentLoad(void) const{
    return numContainers;
}

class Airline
{
    public:
        Airline(int nA321, int nB777, int nB787);
        ~Airline(void);
        void addShipment(int size);
        void printSummary(void) const; // prints a list of airplanes with their current and maximum load.
    
    private:
        const int nAirplanes; // total # of airplanes used by airline
        Airplane** airplaneList; // array of pointers to Airplane objects
};
  
Airline::Airline(int nA321, int nB777, int nB787):nAirplanes(nA321 + nB777 + nB787){
    airplaneList = new Airplane*[nAirplanes];
    for ( int i = 0; i < this->nAirplanes; i++ ){
        airplaneList[i] = new Airplane(10);
        airplaneList[i] -> maxLoad();
        cout << "Airline " << i+1 << " maximum load " << airplaneList[i] << endl;
    }
}

Airline::~Airline(void){}

int main(void)
{
    // create an Airline with 4 A321, 2 B777 and 1 B787
    Airline airline(4,2,1);
    cout << "Assignment complete" << endl;
}

You can use runtime polymorphism:您可以使用运行时多态性:

  • Make your Airplane class virtual pure, so you cannot really instantiate an Airplane .让你的Airplane class 纯虚拟,这样你就不能真正实例化一个Airplane
    virtual int maxLoad() const = 0;
  • Add 3 subclasses to your Airplane class, one for each type of plane.为您的Airplane class 添加 3 个子类,每种类型的飞机一个。 These subclasses will define the maximum number of containers, for example, using an static inline const member.这些子类将定义容器的最大数量,例如,使用static inline const成员。
    static inline const int maxContainers{10};

They will also implement the maxLoad virtual method to return maxContainers .他们还将实现maxLoad虚拟方法以返回maxContainers

    virtual int maxLoad() const override { return maxContainers; }
  • For each airline, keep the airplaneList as an array of Airplane* , but then assign a specific plane instance to each of those pointers:对于每家航空公司,将airplaneList保留为Airplane*的数组,然后为每个指针分配一个特定的飞机实例:
    airplaneList = new Airplane*[nAirplanes];
    int size = 0;
    for (int i = 0; i < nA321; i++, size++) { airplaneList[size] = new A321(); }
    for (int i = 0; i < nB777; i++, size++) { airplaneList[size] = new B777(); }
    for (int i = 0; i < nB787; i++, size++) { airplaneList[size] = new B787(); }
  • And two important points regarding destructors:关于析构函数的两个要点:
  1. Make Airplane destructor virtual.使Airplane析构函数虚拟化。
    Since airplaneList is an array of Airplane pointers created through new , at some point we should do a delete of each of those pointers, and that is going to invoke the Airplane destructor;由于airplaneList是通过new创建的Airplane指针数组,在某些时候我们应该delete每个指针,这将调用Airplane析构函数; however, since we actually created instances of subclasses of Airplane (eg with new A321() ), we need the destructor of the subclass to be executed.然而,由于我们实际上创建了Airplane子类的实例(例如使用new A321() ),我们需要执行子类的析构函数。
    That won't be possible if the Airplane destructor is not virtual.如果Airplane析构函数不是虚拟的,那将是不可能的。
    virtual ~Airplane() {};
  1. Airline constructor is doing a new[] for the airplane list, and a new for each airplane. Airline constructor 正在为飞机列表做一个new new[] ,并为每架飞机做一个 new。 Airline destructor should do the correspondings delete[] and delete . Airline析构函数应该执行相应的delete[]delete
Airline::~Airline()
{
    for (int i = 0; i < nAirplanes; i++) { delete airplaneList[i]; }
    delete[] airplaneList;
}

[Demo] [演示]

// Outputs:
//
//   Airplane 1 (A321): maximum load = 10
//   Airplane 2 (A321): maximum load = 10
//   Airplane 3 (A321): maximum load = 10
//   Airplane 4 (A321): maximum load = 10
//   Airplane 5 (B777): maximum load = 32
//   Airplane 6 (B777): maximum load = 32
//   Airplane 7 (B787): maximum load = 40
//   Assignment complete

As an aside note, using a std::vector for the airplaneList , and smart pointers (eg std::unique_ptr ) to the airplane instances would simplify the code a lot:附带说明一下,使用std::vector作为airplaneList和指向飞机实例的智能指针(例如std::unique_ptr )会大大简化代码:

  • You wouldn't need the heap allocation for the airplane list.您不需要飞机列表的堆分配。
  • You wouldn't need to care about deleting the heap instances for the airplanes and the airplane list.您不需要关心删除飞机和飞机列表的堆实例。

[Demo] [演示]

class Airline
{
public:
    Airline(int nA321, int nB777, int nB787);
    ~Airline() {}
    void addShipment(int size);
    void printSummary(void) const; // prints a list of airplanes with their current and maximum load.

private:
    int nAirplanes{}; // total # of airplanes used by airline
    std::vector<std::unique_ptr<Airplane>> airplaneList{}; // array of pointers to Airplane objects
};
  
Airline::Airline(int nA321, int nB777, int nB787)
: nAirplanes(nA321 + nB777 + nB787)
{
    for (auto i = 0; i < nA321; i++) { airplaneList.emplace_back(std::make_unique<A321>()); }
    for (auto i = 0; i < nB777; i++) { airplaneList.emplace_back(std::make_unique<B777>()); }
    for (auto i = 0; i < nB787; i++) { airplaneList.emplace_back(std::make_unique<B787>()); }

    for (size_t i = 0; i < airplaneList.size(); i++)
    {
        std::cout
            << "Airplane " << i+1
            << " (" << airplaneList[i]->getName() << ")"
            << ": maximum load = " << airplaneList[i]->maxLoad() << "\n";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM