#c #c 11 #operator-overloading #bigint
Вопрос:
В настоящее время у меня есть задание, в котором я должен создать свой собственный класс BigInt. Проблема, с которой я сталкиваюсь, заключается в том, что я не уверен, как я смогу перегрузить оператор ввода так же, как я перегрузил =.
Мой файл заголовка выглядит следующим образом:
#ifndef BIGINT_BIGINT_H
#define BIGINT_BIGINT_H
#include <iostream>
#define BIGINT_SIZE 256
class Bigint {
public:
friend std::ostreamamp; operator>> (std::ostreamamp; out, const Bigintamp; n);
friend std::ostreamamp; operator<< (std::ostreamamp; out, const Bigintamp; n);
// the binary operator
Bigint operator (const Bigintamp; n);
// the binary - operator
Bigint operator- (const Bigintamp; n);
// the binary * operator
Bigint operator* (const Bigintamp; n);
// the binary / operator
Bigint operator/ (const Bigintamp; n);
// the binary = operator: bigint = bigint
Bigintamp; operator= (const Bigintamp; n);
// the binary = operator with int: bigint = int
Bigintamp; operator= (int n);
// the constructor and destructor
Bigint(int size = BIGINT_SIZE) {digits = size; number = new char[digits]; }
~Bigint() { delete[] number; }
private:
int digits;
char *number;
};
#endif //BIGINT_BIGINT_H
И мой файл cpp таков:
#include "Bigint.h"
#include <iostream>
std::istreamamp; operator>> () {
}
std::ostreamamp; operator<< (std::ostreamamp; out, const Bigintamp; n) {
int cntr = 0;
while ((n.number[cntr] == 0) amp;amp; (cntr < n.digits-1))
cntr ;
while (cntr < n.digits)
out << (int)n.number[cntr ];
return out;
}
Bigintamp; Bigint::operator= (int n) {
int cntr;
cntr = digits - 1;
while (cntr >= 0) {
number[cntr--] = n % 10;
n /= 10;
}
return *this;
}
Bigint Bigint::operator (const Bigintamp; n) {
Bigint sum( (digits > n.digits) ? digits : n.digits );
int nptr, myptr, sumptr;
char next_n1, next_n2;
char carry = 0;
for (sumptr = sum.digits - 1, myptr = digits - 1, nptr = n.digits - 1; sumptr >= 0; sumptr--, myptr--, nptr--) {
next_n1 = (nptr < 0) ? 0 : n.number[nptr];
next_n2 = (myptr < 0) ? 0 : number[myptr];
sum.number[sumptr] = next_n1 next_n2 carry;
if (sum.number[sumptr] > 9) {
carry = 1;
sum.number[sumptr] -= 10;
}
else{
carry = 0;
}
}
return sum;
}
До сих пор я фактически реализовал код только для обработки и =.
Комментарии:
1. Предложение: Сделайте
Bigint operator (const Bigintamp; n);
и тому подобное бесплатными функциями. Добавьте функции-члены, напримерBigintamp; operator =(const Bigintamp; n);
, вместо этого. Затем свободные функции могут использовать функции-члены. Если вы хотите сохранитьBigint operator (const Bigintamp; n);
etc в качестве функций-членов, они должны бытьBigint operator (const Bigintamp; n) const;
2. Пожалуйста, добавьте немного больше деталей реализации вашего класса. Как вы собираетесь хранить байты в
char
массиве. Простые символы ASCII, двоичная или какая-то другая кодировка? Маленький эндианец, большой эндианец? Как вы отслеживаете доступное пространство вBigint
objectct?
Ответ №1:
Первый
friend std::ostreamamp; operator>> (std::ostreamamp; out, const Bigintamp; n);
должно быть
friend std::istreamamp; operator>> (std::istreamamp; in, Bigintamp; n);
для перегрузки оператора ввода.
Тогда в файле .cpp определение будет примерно таким:
std::istreamamp; operator>> (std::istreamamp; in, Bigintamp; n)
{
//take the inputs you want
in >> n.digits;
if (in) // check that the inputs succeeded
{
//do something if succeded
}
else
{
//n = Bigint();//usually we set n to a default constructed object
}
return in;
}
if
Проверяет, были ли считывания успешными. Если по какой-либо причине возникает ошибка ввода-вывода, оператор сбрасывает данный объект в пустое значение Bigint. Таким образом, объект гарантированно будет находиться в согласованном состоянии.
Обратите также const
внимание, что для второго параметра оператора ввода это не требуется n
, потому что мы изменим его состояние внутри тела.