我想访问一个对象的成员变量

时间:2014-09-14 21:34:56

标签: c++

在上课时,我如何区分两个不同的类变量。我想在两个向量中添加元素并获得一个带有两个不同数字之和的新向量。在下面的代码中,当我创建一个类的实例时,我可以访问它的向量,但参数中的那个呢? number_blocks是BigInt类中的向量变量

    BigInt BigInt::add(const BigInt& number){
      int flag = 0;
      int carry = 0;
      int sum = 0;
      const int LIMIT = 9;
      int size = number.length();
      for(int i = 0; i < size; i++){
        sum = number_blocks[i]// + number_blocks_number[i];
        if(flag == 1){
          sum = sum + carry;
          flag = 0;
        }
        if(sum > LIMIT){
          carry = sum / 10;
          sum = sum % 10;
          flag = 1;
        }
        number_blocks.push_back(sum);
      }


  return BigInt();
}

2 个答案:

答案 0 :(得分:0)

number.length()

相同
number.number_blocks[i]
顺便说一句:你必须在最后推动进位(如果非零)。

注意:请询问具体问题。 &#34;我想访问一个对象的成员变量&#34;。显示一个单线示例。没有人关心其余的事情。

答案 1 :(得分:0)

我在您BigInt::add的实施中看到的问题:

  1. 您将在行中返回BigInt的默认实例:

    return BigInt();
    

    我觉得你会返回一个BigInt,这是添加两个BigInt的结果。

  2. 您没有考虑不同长度的BigInt。例如,使用187添加85

  3. 你忽略了最后一次携带。如果您添加99,则需要随身携带1

  4. 计算总和和进位的逻辑可以简化为:

    sum = this->number_blocks[i] + number.number_blocks[i] + carry;
    carry = sum / 10;
    sum = sum % 10;
    

    您不需要变量flagLIMIT

  5. 这是解决这些问题的实现。

    BigInt BigInt::add(const BigInt& number){
       int carry = 0;
       int sum = 0;
    
       // Compute the minimum number of digits from both the numbers.
       size_t size1 = this->length();
       size_t size2 = number.length();
       size_t size = size1 < size2 ? size1 : size2;
    
       BigInt ret;
    
       // Process the digits that are in both the the first number and the
       // second number.
       for(size_t i = 0; i < size; i++)
       {
          sum = this->number_blocks[i] + number.number_blocks[i] + carry;
          carry = sum / 10;
          sum = sum % 10;
          ret.number_blocks.push_back(sum);
       }
    
       // If the first number has more digits than the second, deal with the
       // remaining digits from the first number.
       if ( size1 > size )
       {
          for(size_t i = size; i < size1; i++)
          {
             sum = this->number_blocks[i] + carry;
             carry = sum / 10;
             sum = sum % 10;
             ret.number_blocks.push_back(sum);
          }
       }
    
       // If the second number has more digits than the first, deal with the
       // remaining digits from the second number.
       else if ( size2 > size )
       {
          for(size_t i = size; i < size2; i++)
          {
             sum = number.number_blocks[i] + carry;
             carry = sum / 10;
             sum = sum % 10;
             ret.number_blocks.push_back(sum);
          }
       }
    
       // Deal with the last carry.
       if ( carry > 0 )
       {
          ret.number_blocks.push_back(carry);
       }
    
       return ret;
    }