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

如何更新getter返回的变量?让front()/back()支持赋值操作

解决front()/back()可赋值的问题

嘿,我一眼就看出你卡在哪了!你现在的front()和back()返回的是T类型的值副本——这意味着调用vectD3.front()时,你拿到的是数组第一个元素的拷贝,给这个临时拷贝赋值不仅不会影响原数组,还会触发编译器报错,因为右值不能被当作左值赋值。

核心解决方案:返回引用而非值

要让这些方法支持赋值操作,你需要把返回类型改成非const引用(T&),这样返回的就是数组元素本身的别名,而非副本。同时为了兼容const对象的调用场景,最好再重载一个const版本的方法。

修改后的完整代码如下:

// 非const版本:支持赋值操作,返回元素的可修改引用
public:
T& front() { 
    if(currentSize > 0) { 
        return array[0]; 
    } else { 
        throw std::runtime_error("dynarray has no members"); 
    } 
}

T& back() { 
    if(currentSize > 0) { 
        return array[currentSize - 1]; 
    } else { 
        throw std::runtime_error("dynarray has no members"); 
    } 
}

// const版本:支持const对象调用,返回只读引用
public:
const T& front() const { 
    if(currentSize > 0) { 
        return array[0]; 
    } else { 
        throw std::runtime_error("dynarray has no members"); 
    } 
}

const T& back() const { 
    if(currentSize > 0) { 
        return array[currentSize - 1]; 
    } else { 
        throw std::runtime_error("dynarray has no members"); 
    } 
}

为什么这样能解决问题?

  • 非const版本返回T&时,vectD3.front()直接指向原数组的第一个元素,赋值操作会直接修改原数组内容,完全符合你的需求;
  • 新增的const版本是为了代码健壮性:如果你的dynarray对象是const类型(比如const DynArray<char> vectD3;),它只能调用const方法,此时返回的const T&只能读取值,不能赋值,完美契合const语义。

这样修改后,你原来的vectD3.front() = '{'; vectD3.back() = '}';就能正常运行,不会再报错了。

内容的提问来源于stack exchange,提问作者Chase Gee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:51:32