这是C++程序,大约加两个数字

This is C++ program, about add two numbers

本文关键字:两个 数字 程序 C++ 这是      更新时间:2023-10-16

这是太平洋问题。类LargeInt的实现将使用动态物理结构来存储整数的各个数字,并将提供一些可以对整数执行的基本 I/O 和算术运算。

特别是,该类应包括:

  1. 默认构造函数
  2. 使operator +重载的运算符函数
  3. 使operator ==重载的运算符函数
  4. 使operator <<过载的运算符函数
  5. 使operator >>重载的运算符函数

注意 1:由于 LargeInt 类不包含指针,因此不需要复制构造函数或析构函数。

#include "targetver.h"
using namespace std;
class LargeInt
{
private:
  char datain[200];
  int databit[200];
  int len;
  int overflow;
  LargeInt(char *x, int inlen)
  {
    int i = 0;
    int j = inlen - 1;
    len = inlen;
    overflow = 0;
    for (i = 0; i < 200; i++)
    {
      databit[i] = 0;
      datain[i] = '';
    }
    for (i = 0; i < len; i++)
    {
      datain[i] = x[j];
      j--;
    }
  }
  ~LargeInt();
  void GetDataBit()
  {
    int i = 0;
    for (i; i < len; i++)
      databit[i] = datain[i] - 48;
  }
public:
  LargeInt& operator+(LargeInt& data);
  bool operator==(LargeInt& data);
  LargeInt& operator>>(int x);
  LargeInt& operator<<(int x);
};
bool LargeInt::operator==(LargeInt& data)
{
  if (this->len != data.len)
    return false;
  else
  {
    for (int i = 0; i < 200; i++)
    {
      if (this->databit[i] == data.databit[i])
        continue;
      else
        return false;
    }
    return true;
  }
}
LargeInt& LargeInt::operator+(LargeInt& data)
{
  LargeInt t("0", 0);
  int addlen;
  if (this->len > data.len)
    addlen = this->len;
  else
    addlen = data.len;
  for (int i = 0; i < addlen; i--)
  {
    t.databit[i] = (data.databit[i] + this->databit[i] + t.overflow) % 10;
    if ((data.databit[i] + this->databit[i] + t.overflow) >= 10)
      t.overflow = 1;
  }
  t.len = addlen;
  for (int i = 0; i < addlen; i++)
  {
    t.datain[i] = t.databit[i] + 48;
  }
  return t;
}

当我构建它时,它有一个这样的错误

警告

1 警告 C4172:返回局部变量或临时变量的地址。

LargeInt& LargeInt::operator+(LargeInt& data)

删除 &,您的警告应该会消失。现在,返回引用了一个变量 t,该变量是函数的本地变量,当调用函数捕获返回时,该变量已超出范围。