我想访问对象的成员变量
I want to access a member variable of an object
创建类时,如何区分两个不同的类变量。我想把两个向量中的元素加在一起,得到一个新的向量,它是两个不同数字的和。在下面的代码中,当创建类的实例时,我可以访问它的向量,但参数中的向量呢?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
:的实现中看到的问题
-
您在以下行中返回
BigInt
的默认实例:return BigInt();
对我来说,你会返回一个
BigInt
,这是添加两个BigInt
的结果。 -
您没有考虑不同长度的
BigInt
。例如,将187
与85
相加。 -
您忽略了最后一次进位。如果添加
9
和9
,则需要携带1
。 -
计算总和和进位的逻辑可以简化为:
sum = this->number_blocks[i] + number.number_blocks[i] + carry; carry = sum / 10; sum = sum % 10;
您不需要变量
flag
和LIMIT
。
下面是一个解决这些问题的实现。
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;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查