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

重载构造函数配合byteAdd函数无法输出正确求和结果求助

问题排查:byteAdd函数输出始终为0的原因及修复方案

问题描述

我尝试创建一个接收整数的重载构造函数,通过byteAdd函数实现两数相加。但编译运行后,输出始终是默认构造函数的初始值0,而非两数之和(例如obj5(5)与obj6(5)相加应得10,二进制字符串为00001010)。曾在setValue()函数中使用clear函数,但问题仍存在,恳请帮忙排查代码问题。

原始代码

Math.h

#pragma once
#ifndef MATH
#define MATH

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>


using std::string;
using std::vector;

class Math {

private:

    int num1{};
    int bitsToInt() const;

public:
    void setValue(int value);
    int at(int index) const;
    string toString() const;
    int toInt() const;

    struct Bits {
        int value;
        Bits(int v) : value(v) {}
    };
    
    vector<Bits>bits; 
    Math byteAdd(const Math& f);

    //Constructor
    Math();//Default constructor
    Math(int val); //This is an overloaded constr
    
};

#endif // !MATH

Math.cpp

#include <iostream>
#include <cstdlib>
#include "Math.h"


using namespace std;

//Default Math constructor
Math::Math() {
    this->setValue(0);
}

//Overloaded Constructor
Math::Math(int val) {
    this->setValue(val);
    for (int i = 0; i < 8; ++i) {
        this->bits.push_back(Bits{ (val >> i) & 1 });
    }
}

void Math::setValue(int value) {
    this->num1 = value;
    for (int i = 0; i < 8; ++i) {
        this->bits.push_back(Bits{ (value >> i) & 1 });
    }
}

int Math::bitsToInt() const {
    int val1 = 0;
    for (int i = 0; i < 8; i++) {
        val1 |= (bits[i].value << i);
    }
    return val1;
}

int Math::at(int index) const {
    return bits[index].value;
}

std::string Math::toString() const {
    std::string str;
    for (int i = 7; i >= 0; --i) {
        str += std::to_string(bits[i].value);
    }
    return str;
}

int Math::toInt() const {
    return bitsToInt();
}

Math Math::byteAdd(const Math& f) {
    Math tmp;
    tmp.num1 = num1; // Assigning num1 of current object to num1 of tmp 
    int carry = 0;

    for (int i = 0; i < 8; ++i) {
        int s = bits[i].value + f.bits[i].value + carry; // Accessing bits of f
        tmp.bits.push_back(Bits{ s % 2 }); // Using push_back to add new Bits
        carry = s / 2;
    }
    return tmp;
}

Main.cpp

#include <iostream>
#include "Math.h"

using namespace std;

int main() {

    Math obj1, obj2, obj4, obj5(5), obj6(5);
    Math obj3 = obj1.byteAdd(obj2);
    Math obj7 = obj5.byteAdd(obj6);

    cout << "Int: " << obj7.toInt() << endl;
    cout << "String " << obj7.toString() << endl;

    return 0;
}

问题分析

导致输出始终为0的核心原因有三个:

  • 重复填充bits向量:重载构造函数调用setValue后,又手动循环往bits中添加8个元素,导致bits长度变为16。但bitsToInt和toString仅读取前8个元素,这部分数据会因重复填充出现混乱。
  • byteAdd中tmp的bits未清空:默认构造的tmp通过setValue(0)已填充8个0元素,后续byteAdd又追加8个相加结果,导致tmp.bits有16个元素。但bitsToInt只处理前8个初始0,完全忽略了后面的相加结果。
  • num1变量未同步更新:byteAdd中手动给tmp.num1赋值为当前对象的num1,未计算相加后的正确值,导致num1与bits数据不一致。

修复方案及代码

修复点说明

  1. 修改setValue函数:每次设置值前先清空bits向量,避免重复填充。
  2. 简化重载构造函数:移除重复的bits填充逻辑,依赖setValue完成初始化。
  3. 修复byteAdd函数:清空tmp的bits向量后再填充相加结果,同时同步更新num1变量。

修复后的Math.cpp代码

#include <iostream>
#include <cstdlib>
#include "Math.h"

using namespace std;

//Default Math constructor
Math::Math() {
    this->setValue(0);
}

//Overloaded Constructor
Math::Math(int val) {
    this->setValue(val);
}

void Math::setValue(int value) {
    this->num1 = value;
    this->bits.clear(); // 先清空原有元素,避免重复填充
    for (int i = 0; i < 8; ++i) {
        this->bits.push_back(Bits{ (value >> i) & 1 });
    }
}

int Math::bitsToInt() const {
    int val1 = 0;
    for (int i = 0; i < 8; i++) {
        val1 |= (bits[i].value << i);
    }
    return val1;
}

int Math::at(int index) const {
    return bits[index].value;
}

std::string Math::toString() const {
    std::string str;
    for (int i = 7; i >= 0; --i) {
        str += std::to_string(bits[i].value);
    }
    return str;
}

int Math::toInt() const {
    return bitsToInt();
}

Math Math::byteAdd(const Math& f) {
    Math tmp;
    tmp.bits.clear(); // 清空默认构造时填充的0元素
    int carry = 0;
    int result_num = 0;

    for (int i = 0; i < 8; ++i) {
        int s = bits[i].value + f.bits[i].value + carry;
        tmp.bits.push_back(Bits{ s % 2 });
        carry = s / 2;
        // 同步计算num1的正确值
        if (tmp.bits[i].value) {
            result_num |= (1 << i);
        }
    }
    tmp.num1 = result_num;
    return tmp;
}

运行结果

修复后运行Main.cpp,输出将符合预期:

Int: 10
String 00001010

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:05:01