微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

调整抽象类中嵌套类对象的向量大小

如何解决调整抽象类中嵌套类对象的向量大小

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

基类和抽象类 = AbstractHex ||嵌套类 = Cell ||衍生的 类 = 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());
    }
}

解决方法

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

之前:

class Cell{
            public:
                explicit Cell();

之后:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。