添加两个字符列表
在此问题中,用户输入两个数字。每个数字代表一个整数,其字符存储在一个列表中。我需要修改 + 运算符,以便程序将获取两个列表字符,将它们更改为整数,添加它们,然后将其更改回字符列表。我知道这很令人困惑,但希望代码能帮助澄清问题:
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 类的头文件。还有其他部分,例如构造函数、析构函数等,但在本例中这些是唯一重要的事情。我不知道如何在实现文件中编写运算符+定义的代码。有什么想法吗?
In this problem, the user enters in two numbers. Each number represents an integer, whose characters are stored into a list. I need to modify the + operator, so that the program will take the two list characters, change them to ints, add them, and then change it back to a char list. Its confusing I know, but hopefully the code will help clear things up:
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
}
This is the header file for the LongInt class. There are other parts too it such as a constructor, destructor, etc, but these are the only things that matter in this case. I don't know how to go about writing the code for the operator+ definition in the implementation file. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样启动该函数:
该函数定义将位于类定义之外(大概在
.cpp
实现文件中)。在此函数内,您可以使用普通的普通加法(添加相应数字对、处理任何进位等)来添加参数
x
和y
。在本地LongInt
对象中构建结果,并从operator+()
函数返回计算值。如果尚未为您决定,您需要决定最低有效数字是在您的
val
列表中第一个还是最后 。两种方式都是有效的,但其中一种选择可能比另一种更容易使用(我将让您决定哪一种)。You would start the function something like this:
This function definition would go outside the class definition (presumably in a
.cpp
implementation file).Inside this function, you would add the parameters
x
andy
using normal longhand addition (add pairs of corresponding digits, handle any carry, etc). Build up the result in a localLongInt
object, and return the computed value from youroperator+()
function.If it hasn't already been decided for you, you will need to decide whether the least significant digit comes first or last in your
val
list. Either way is valid, but one choice is likely to be easier to work with than the other (I'll let you decide which one).如果你想将字符列表转换为 int,你可以这样做:
If you want to convert the list of chars to an int, you can do something like this: