You need to enable JavaScript to run this app. C++类自定义setter函数执行后未生效的问题解析
优惠活动
大模型
产品
解决方案
定价
更多

C++类自定义setter函数执行后未生效的问题解析

代码问题排查

根本原因

你实现的setter函数本身没有逻辑错误,之所以看起来不生效,是因为yourMom函数里调用setter修改的对象,和你在main函数里打印的对象根本不是同一个。
在yourMom函数内部,你写了一行Test example{};,这会在这个函数的局部作用域内新建一个完全独立的Test实例:

void yourMom(std::string test1, std::string test2) {
    Test example{}; // 独立的临时局部对象
    int Integer1 = std::stoi(test1);
    int Integer2 = std::stoi(test2);
    example.setA(Integer1);
    example.setB(Integer2);
}

C++的局部变量仅在所属的函数块执行期间有效,当yourMom函数执行结束时,这个内部新建的局部example会被直接销毁,所有通过setter对它做的修改会跟着一起消失,完全不会影响main函数里你初始创建的那个example实例。
这就是两次打印结果完全一致的核心原因。

修正方式

要让setter修改main函数里的目标对象,你需要把对象的引用传入函数,而不是在函数内部新建临时实例:

  1. 修改yourMom的函数签名,增加一个Test&类型的引用参数,避免拷贝生成新对象
  2. 删除函数内部新建Test实例的代码,直接对传入的引用对象调用setter
  3. 在main函数调用yourMom时,把你要修改的example实例作为参数传入
    修正后的核心代码片段:
// 函数接收Test的引用,直接操作传入的原对象,不生成新副本
void yourMom(Test& target, std::string test1, std::string test2) {
    int Integer1 = std::stoi(test1);
    int Integer2 = std::stoi(test2);
    target.setA(Integer1);
    target.setB(Integer2);
}

// main函数内的调用代码
yourMom(example, a_str, b_str);

修正后再运行代码,第二次打印的输出就会变成12 45,符合预期效果。

其他可优化的代码细节

  • 代码里char * string; string = "12 45";的写法不符合现代C++规范:字符串常量是const char*类型,直接赋值给非const的char*会触发编译警告,建议直接写成std::string str = "12 45";,省去类型转换的冗余步骤
  • 定义后从未使用的变量std::string operation{};、未实际用到的头文件<chrono>和<thread>,都可以删除,减少不必要的编译开销
  • yourMom的函数名没有实际语义,建议替换成能体现功能的命名(比如parseInputAndUpdateValues),提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 22:36:02