【发布时间】:2014-12-24 17:08:53
【问题描述】:
我目前正在做一项学校作业(很抱歉,我的问题是关于我的作业,但我不是在问代码中使用的算法)。我现在正在做算术部分,加法和减法。由于只有两个运算符,因此有 8 种运算组合。在我的程序中,我可以做到这四种情况:
(+a)+(+b)
(-a)+(-b)
(-a)-(+b)
(+a)-(-b)
但是,我无法弄清楚其他四种情况的方法, 即
(+a)+(-b)
(-a)+(+b)
(-a)-(-b)
(+a)-(+b)
真心希望各位大神能对这四种情况的处理提出建议和意见。
这是我的代码:
linkedListType.h: 是一个普通的链表头文件,这里就不贴出全部代码了。
大整数.h: 这里面的函数很长。因此,我跳过了将它们发布出去。
#ifndef BIG_INTEGER_H
#define BIG_INTEGER_H
#include <stack>
#include <iostream>
#include "linkedListType.h"
using namespace std;
class bigInteger
{
private:
int sign; // set 0 for positive, 1 for negative
linkedListType<int> digits; // internal linked-list for storing digits in reverse order
public:
bigInteger(); // default constructor
bigInteger(const bigInteger& other); // copy constructor
// Overload constructor
// Use an numerical string to construct this bigInteger
// For negative number, the first char in the string is '-'
// e.g. "-12345"
bigInteger(const string& number);
// overload the assignment operator
const bigInteger& operator= (const bigInteger& other);
// Return a new bigInteger that is equal to *this + other
// The contents of this and other should not be modified
bigInteger& operator+ (bigInteger& other);
// Return a new bigInteger that is equal to *this - other
// The contents of this and other should not be modified
bigInteger& operator- (bigInteger& other);
// Print a big integer
// Since the digits are stored in reverse order in the internal
// list, you should print in reverse order
// Print "undefined" if the digits list is empty
friend ostream& operator<<(ostream& os, bigInteger& n);
};
【问题讨论】:
-
您应该添加一元运算符 - 例如见here。还要注意它不应该是
bigInteger& operator+ (bigInteger& other);而是bigInteger operator+(const bigInteger& other);即返回 by value 并通过const引用获取参数。你可能想写bigInteger& operator+=(const bigInteger& other);(和operator-=),然后你可以把+写成这样的非成员函数:bigInteger operator+(bigInteger lgs, const bigInteger& rhs) { return lhs += rhs; }。 -
同样,
friend ostream& operator<<(ostream& os, bigInteger& n);应该采用const bigInteger& n。 -
感谢您的建议@TonyD。但是,我可以问一些问题吗?您介意解释一下一元运算符的用途吗?还有,+=和-=的作用是什么?
-
我不明白你的问题。而且您发布的代码不太可能足以让任何人帮助您。 (另外,“反向”不是一个词。)
-
@user2847449:当然 - 欢迎提问。假设你有
bigInteger x;并写成-x,如果没有“左侧”可以减去x,编译器将寻找bigInteger bigInteger::operator-()函数并调用它——它应该返回*this的否定- 在上面的链接问题中对此进行了解释。+=和-=从左侧的值中加减一个数量,因此如果运算符“正常”实现,x = x + 3可以方便地缩短为x += 3。如果你写的是+和-,人们也会期待+=和-=。