You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现八皇后问题中子类无法重写父类虚函数问题咨询

问题原因
  • 核心问题触发了C++对象切片(Object Slicing),同时C++的多态虚函数动态绑定只有通过指针/引用调用才会生效:你声明的二维数组std::vector<std::vector<Square> >存储的是Square类型的实例本身,当执行squares[x][y] = Queen(x,y)赋值操作时,只会拷贝Queen对象中属于父类Square的成员,子类特有的虚函数表信息等内容会被直接截断,最终数组中存储的仍然是Square类型的对象,调用printValue自然只会执行父类的实现输出S。
  • 附加问题:Empty类的继承默认是private继承,不符合多态调用的要求,即使没有对象切片问题也无法正常调用子类的printValue。
解决方案
  1. 修改二维数组的存储类型为父类的智能指针,避免对象切片:
// 原来的定义
std::vector<std::vector<Square> > squares;
// 修改后
std::vector<std::vector<std::unique_ptr<Square>>> squares;
  1. 修正Empty类的继承方式为public继承:
class Empty : public Square { // 新增public修饰符
// 原有类代码
};
  1. 给基类Square添加虚析构函数,避免内存泄漏:
class Square{
// 原有类成员
public:
    virtual ~Square() = default; // 新增虚析构函数
// 原有类成员
};
  1. 修改棋盘初始化和setQueen的实现:
// 棋盘初始化阶段,所有位置填充Empty实例
squares[i][j] = std::make_unique<Empty>(i, j);

// setQueen实现修改为替换智能指针指向的对象
void Chessboard::setQueen(int x, int y){
    squares[x][y] = std::make_unique<Queen>(x, y);
}
  1. 打印调用改为通过指针调用虚函数:
squares[i][j]->printValue();

内容的提问来源于stack exchange,提问作者Finley Adams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:15:03