将一个类的对象列表传递给另一个类C ++

时间:2019-04-24 15:01:08

标签: c++

编辑:问题已解决,并且刚刚意识到我可能不希望自己的完整代码在线,因为这可能会触发我的反抄袭行为,即使它是我自己的代码...也不允许我删除帖子

1 个答案:

答案 0 :(得分:1)

不确定ship.h代码是什么(您需要发布所有内容),但是创建一些简单的版本似乎可以正常工作:

#include<string>
#include<iostream>  // to use input and output streams
#include<memory> // to use smart pointers
#include<vector> // to use vectors

struct Ship{};
struct Destroyer : Ship {};

class Board{
private:
    std::unique_ptr<char[]> bdata; // to hold the data about the board
    int rows, columns;
    std::vector<Ship*> shipslist;
public:
    Board(std::vector<Ship*> &list); // Constructor
    ~Board() {} // Destructor
};

Board::Board(std::vector<Ship*> &list) : rows{ 10 }, columns{ 10 }, shipslist{list}
{
    // irrelevant code here
}

int main()
{
    // Make vector of Ships
    std::vector<Ship*> ships;
    ships.push_back(new Destroyer()); // simplified constructor call
    // (Destroyer is a derived class of the abstract base class "Ship")
    Board BoardConfig(ships); // Here is where i want to create a board using a list of ships i have made
return 0;
}

实时:https://godbolt.org/z/r0ye_U