c++ - 调整抽象类中嵌套类对象的向量大小
问题描述
我正在尝试使用多态原理构建一个十六进制游戏。我在抽象类中有一个类。我需要一个 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());
}
}
解决方案
我解决了这个问题。主要原因是我的Cell类的默认构造函数没有定义。当我定义默认构造函数时(我只是在类中声明构造函数后添加了 2 个大括号),我的问题已经解决。
前:
class Cell{
public:
explicit Cell();
后:
class Cell{
public:
explicit Cell(){}; //CURLY BRACKETS FOR DEFINITION
推荐阅读
- python - 如何使用一个顶级列对多索引熊猫数据框进行排序?
- java - 服务器端没有响应(基本的java客户端-服务器)
- excel - 如何将数据从工作表复制到空行上的另一个工作表
- c# - 可变输入检测
- javascript - 将 s3.getObject 响应转换为 File 对象
- swift - MapKit .PLIST DICTIONARY with INT 和 STRING-values = 来自 plist 的带有标题和副标题的多个注释(根据:MapKit Sample WWDC 2017 - 237)
- ruby-on-rails - 导航栏未显示在引导程序上
- java - 调用 GLES32 glGetDebugMessageLog 时出现 UnsupportedOperationException
- sql - 设置基于查询以替换循环以从给定日期填充所有记录的所有月末日期
- image - 将PNG图像转换为XImage格式