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

C++类构造函数给指针数组赋值报modifiable lvalue错误如何解决

错误原因

C++ 原生数组不支持整体赋值操作,数组名toyBox属于不可修改的左值,无法作为赋值运算符的左操作数,因此this->toyBox = {}的写法会触发报错。另外你原代码的类定义结束大括号后缺少分号,也会引发编译错误。

修复方案

方案1:使用成员初始化列表(最推荐)

直接在构造函数的初始化列表中对数组做值初始化,编译器会自动将数组内所有指针元素初始化为nullptr,代码简洁且效率最高:

class ToyBox
{
private:
  Toy *toyBox[5];
  int numberOfItems;

public:
  // 初始化列表完成所有成员的初始化
  ToyBox() : toyBox(), numberOfItems(0)
  {
  }
};

方案2:构造函数体内逐元素赋值

如果你需要在构造函数体内完成初始化,可以遍历数组逐个赋值:

ToyBox()
{
  numberOfItems = 0;
  for(int i = 0; i < 5; i++){
    toyBox[i] = nullptr;
  }
}

也可以用标准库算法std::fill简化写法,需要先引入头文件<algorithm>:

#include <algorithm>

ToyBox()
{
  numberOfItems = 0;
  std::fill(std::begin(toyBox), std::end(toyBox), nullptr);
}

方案3:使用std::array替代原生数组(符合现代C++规范)

C++11起提供的std::array容器完全覆盖原生数组的功能,同时支持整体赋值、边界检查等特性,使用更安全:

#include <array>

class ToyBox
{
private:
  std::array<Toy*, 5> toyBox;
  int numberOfItems;

public:
  ToyBox()
  {
    numberOfItems = 0;
    toyBox = {};
  }
};

内容的提问来源于stack exchange,提问作者Tan Nguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:15:03