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

C++报错“对非常量引用的初始值必须为左值”的原因是什么?

C++临时对象绑定非const引用报错问题解决

错误原因

  • 报错信息Initial value of reference to a non-const must be an lvalue直译为「非常量引用的初始值必须是左值」,问题不来自factorize函数,其本身逻辑完全正常
  • 调用factorize(2)这类函数时,返回的std::vector<int>是临时对象,属于右值
  • 你定义的print_vector入参为std::vector<int>& v,是非常量左值引用,C++语法规则明确禁止非常量左值引用绑定到右值(临时对象),因此触发编译错误

解决方案

最符合当前场景的修改方式:因为print_vector仅需要读取vector内容,不需要修改元素,所以把入参改为常量左值引用即可,常量左值引用支持绑定到临时对象:

// 修改后的print_vector函数
void print_vector(const std::vector<int>& v) {
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

如果后续有需要通过引用修改vector的特殊场景,也可以先将函数返回的临时对象存到本地变量(左值)再传入:

void test_factorize() {
    std::vector<int> res1 = factorize(2);
    print_vector(res1);
    std::vector<int> res2 = factorize(72);
    print_vector(res2);
    std::vector<int> res3 = factorize(196);
    print_vector(res3);
}

完整可运行代码

#include <iostream>
#include <vector>

using namespace std;

void print_vector(const std::vector<int>& v) {
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

std::vector<int> factorize(int n) {
    std::vector<int> answer;
    for (int i = 1;i < n + 1; ++i) {
        if (n % i == 0) {
            answer.push_back(i);
        }
    }
    return answer;
}

void test_factorize() {
    print_vector(factorize(2));
    print_vector(factorize(72));
    print_vector(factorize(196));
}

int main() {
    test_factorize();
    return 0;
}

内容的提问来源于stack exchange,提问作者Chloe Martinez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:45:04