帮助重载c ++类运算符 [英] help overloading a c++ class operators
问题描述
你好家伙
i需要以下课程的帮助
这里是hpp文件:
hello guys
i need some help with the following class
here is the hpp file :
#include "iostream"
using namespace std;
#include "string"
#include "vector"
class Mint{
public:
Mint();
Mint(int);
Mint(const char*);
Mint operator+=(const Mint &rhs);
bool operator<(const Mint&);
bool operator>(const Mint&);
void display();
private:
unsigned char* num;
int size;
};
这里是cpp文件
and here is the cpp file
#include "Mint.h"
Mint::Mint()
{
num = new unsigned char[size= 1];
num[0] = 0;
}
Mint::Mint(const char* s)
{
num = new unsigned char[size= strlen(s)/2 + strlen(s)%2];
if(strlen(s)%2 == 1)
num[0] = s[0]-'0';
unsigned int i;
int j=strlen(s)%2;
for(i=strlen(s)%2;i<strlen(s);i+=2)
{
int left = s[i] - '0';
int right = s[i+1] - '0';
num[j] = left << 4 ;
num[j] |= right;
j++;
}
}
Mint Mint::operator+=(const Mint &rhs){
int i,carry=0,sum;
for(i=this->size-1;i>=0;i--)
{
sum = ((num[i] ^ rhs.num[i]) ^ carry);
carry = ((num[i] & rhs.num[i]) | (num[i] & carry)) | (rhs.num[i] & carry);
num[i] = sum;
}
return *this;
}
bool Mint::operator<(const Mint& rhs)
{
unsigned int i;
if (size < rhs.size)
return true;
if (size == rhs.size)
for(i=0;i<size;i++)
{
if(num[i] < rhs.num[i])
return true;
}
return false;
}
bool Mint::operator>(const Mint& rhs)
{
if (*this < rhs)
return false;
return true;
}
void Mint::display()
{
int i;
for (i=0;i<size ;i++)
{
int first_digit = (num[i] & '\xF0')>>4;
int second_digit = (num[i] & '\x0F');
if (i || first_digit)
cout << first_digit;
if (i || second_digit)
cout << second_digit;
}
}
想法是使用int无法处理的大数字但是你可以看到我拿了几个数字并将它们存储在一个字节中,每个字节占4位
现在我需要帮助+ - 和*运算符
i尝试了一下但是它没有用,所以请查看代码并给我你的建议
the idea is to work with big numbers that an int can't handle but as you can see i took each couple of digits and store them in one byte each taking 4 bits
now i need help with + - and * operators
i gave it a try but it didn't work so please check out the code and give me your suggestions
推荐答案
i没有实现+如果我做了我会用它+ =
这是我的问题我不知道如何实现+也没有+ =
如果你知道如何实现它请
帮助我因为我被卡住了
i didn't implement + either if i did i would have used it in +=
that is my problem i don't know how to implement + nor +=
please if you know how to implement it
help me because i'm stuck
也许你必须从
运算符重载 - cppreference.com [ ^ ],
C ++中的运算符重载 - Cprogramming.com [ ^ ]。
在上面引用的最后一篇文章中,最接近你的案例是Complex类的代码示例;显示+运算符的实现。
Perhaps you have to start with
operator overloading — cppreference.com[^],
Operator Overloading in C++ - Cprogramming.com[^].
In last of the articles referenced above, the case closest to yours is the code sample of class "Complex"; implementation of + operator is shown.
这篇关于帮助重载c ++类运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!