首页 > 解决方案 > 调整抽象类中嵌套类对象的向量大小

问题描述

我正在尝试使用多态原理构建一个十六进制游戏。我在抽象类中有一个类。我需要一个 Cells 的 2D 向量(嵌套类),但是当我尝试实现一个函数来调整向量大小时出现此错误。

基类和抽象类 = AbstractHex || 嵌套类 = 单元 || 派生类 = HexVector

这是我得到的(错误):

/usr/bin/ld: /tmp/ccq9PAk3.o: in function `void std::_Construct<HexGame::AbstractHex::Cell>(HexGame::AbstractHex::Cell*)':HexVector.cpp:(.text._ZSt10_ConstructIN7HexGame11AbstractHex4CellEJEEvPT_DpOT0_[_ZSt10_ConstructIN7HexGame11AbstractHex4CellEJEEvPT_DpOT0_]+0x2d): undefined reference to `HexGame::AbstractHex::Cell::Cell()' collect2: error: ld returned 1 exit status

我的基类(抽象):

namespace HexGame{
   class AbstractHex{

     public:
        class Cell{
                public:
                    explicit Cell();
                    explicit Cell(int rw,int col) : row(rw) , column(col){} //INTENTIONALLY EMPTY
                    explicit Cell(int rw,int col, char p) : row(rw) , column(col) , point(p){} 
                                         //INTENTIONALLY EMPTY
                    int getRow()const {return row;};
                    int getColumn()const {return column;};
                    void setRow(int index) {row = index;};
                    void setColumn(int index) {column = index;};
                    int getPoint()const {return point;};
                    void setPoint(char param) {point = param;};    
                private:
                    int row;
                    int column;
                    char point;
            };

     virtual void setSize() = 0;

     private:
       int board_size;

我正在调用抽象类中的 setSize() 函数。我可以在抽象类中的非虚函数中调用虚函数吗?

void AbstractHex::startGame(){ //non-virtual function in Abstract Class
setSize(); //virtual function in Abstract Class
//I'm calling startGame() function every time I create an object of HexVector
}

我的派生类:

class HexVector : public AbstractHex{
    public:
        void setSize() override;
    private:
        vector<vector<AbstractHex::Cell> > board;

覆盖 setSize() 函数

void HexVector::setSize(){
 board.resize(getBoardSize());
    for(int i=0; i<getBoardSize(); i++){
        board[i].resize(getBoardSize());
    }
}

标签: c++c++11vectorpolymorphism

解决方案


我解决了这个问题。主要原因是我的Cell类的默认构造函数没有定义。当我定义默认构造函数时(我只是在类中声明构造函数后添加了 2 个大括号),我的问题已经解决。

前:

class Cell{
            public:
                explicit Cell();

后:

class Cell{
            public:
                explicit Cell(){}; //CURLY BRACKETS FOR DEFINITION

推荐阅读