我想访问对象的成员变量

I want to access a member variable of an object

本文关键字:成员 变量 对象 访问      更新时间:2023-10-16

创建类时,如何区分两个不同的类变量。我想把两个向量中的元素加在一起,得到一个新的向量,它是两个不同数字的和。在下面的代码中,当创建类的实例时,我可以访问它的向量,但参数中的向量呢?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();
}

number.length() 相同

number.number_blocks[i]

BTW:你必须在末尾推动进位(如果非零)。

注意:请提出具体问题。"我想访问对象的成员变量"。显示一个单行示例。没有人关心其余的。

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

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

    return BigInt();
    

    对我来说,你会返回一个BigInt,这是添加两个BigInt的结果。

  2. 您没有考虑不同长度的BigInt。例如,将18785相加。

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

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

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

    您不需要变量flagLIMIT

下面是一个解决这些问题的实现。

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;
}