【问题标题】:Adding two lists of characters添加两个字符列表
【发布时间】:2011-04-06 03:11:32
【问题描述】:

在这个问题中,用户输入了两个数字。每个数字代表一个整数,其字符存储在一个列表中。我需要修改 + 运算符,以便程序将获取两个列表字符,将它们更改为 int,添加它们,然后将其更改回 char 列表。我知道这很令人困惑,但希望代码能帮助解决问题:

class LongInt
{
public:
    friend LongInt operator+(const LongInt& x, const LongInt& y); //This function will add the value of the two integers which are represented by x and y's character list (val).

private:
    list<char> val; //the list of characters that represent the integer the user inputted

}

这是 LongInt 类的头文件。还有其他部分,例如构造函数、析构函数等,但在这种情况下,这些是唯一重要的事情。我不知道如何在实现文件中编写 operator+ 定义的代码。有什么想法吗?

【问题讨论】:

  • 如果这是家庭作业,那么你应该这样标记它。

标签: c++ list operators overriding definition


【解决方案1】:

你会像这样启动函数:

LongInt operator+(const LongInt& x, const LongInt& y) {
    // code goes here
}

此函数定义将类定义之外(可能在.cpp 实现文件中)。

在此函数中,您可以使用普通的普通加法添加参数xy(添加相应数字对,处理任何进位等)。在本地 LongInt 对象中构建结果,并从您的 operator+() 函数返回计算值。

如果还没有为您决定,您需要决定val 列表中的最低有效数字是first 还是last。任何一种方式都有效,但一种选择可能比另一种更容易使用(我会让你决定哪一种)。

【讨论】:

  • 有没有办法将字符列表转换为字符数组?这样我可以使用 Atoi() 将一组字符转换为一个连贯的 int?
  • @Ctak:我只是在这里猜测,但名称 LongInt 提供了一个线索,即此类可能旨在用于太大无法适合常规 C++ int。因此,无法调用atoi()
【解决方案2】:

如果要将字符列表转换为 int,可以执行以下操作:

std::list<char> digits;
int value = 0;
for(std::list<char>::iterator it = digits.begin(); 
    it != digits.end(); 
    ++it)
{
  value = value * 10 + *it - '0';
}

【讨论】:

  • “*10”是什么意思?
  • 我假设数字是十进制的,所以值为 sum(digit(i) * 10 ^ i)。
  • 我为反向迭代器的错误道歉。它应该是一个普通的迭代器。从最高有效数字开始并迭代到最低有效数字。然后将当前值乘以 10 并添加当前数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多