本身是一个网友发帖子问的.我帮他把加法搞定了.减法以后补上.
#include <iostream.h>
#include "string.h"
class MyInt
{
char* Integer;
bool Negative;
public:
MyInt(){};
MyInt(int len);
MyInt(char* s);
//~MyInt(); 此处不用.系统用自动收回.主要是字符串的空间,另起一函数来释放.
const void operator=(MyInt s) //同类不需要用&
{
Integer=new char[strlen(s.Integer)+1]; //私有成员一样访问.
strcpy(Integer,s.Integer);
Negative=s.Negative;
}
friend MyInt operator+(const MyInt &left,const MyInt &right); //声明友元
void Display(){
for(int i=strlen(Integer)-1;i>=0;i--)//要倒序输出
cout<<Integer[i];
cout<<endl;
}
void freeInt() //在此处释放空间 释放时调用即可.类成员只提供一个CHAR *的指针,指针所指空间不应由本类释放.
{
delete Integer;
}
};
MyInt::MyInt(int len)
{
Integer=new char[len];
Negative=false;
}
MyInt::MyInt(char* s)
{
int i=strlen(s),j=0,t=0;
Negative=false;
if(s[0]=='-'||s[0]=='+') //判断s的符号问题,如果是负号就存,其他情况不存
{
t=1;
if(s[0]=='-')
Negative=true;
Integer=new char[i]; / 改了
}
else Integer=new char[i+1]; / 改了
i--;
while (i>=t)
{
if (s[i]<'0'||s[i]>'9')
{
cout<<"set error"<<endl;
i=-1;
}
else {Integer[j] = s[i];--i; ++j;} //将s存进Integer
}
Integer[j]='/0';
}
MyInt operator+(const MyInt &left,const MyInt &right) //最好引用返回.不用也一样.
{
int i, j=0;int a;
int leftlen=strlen(left.Integer);
int rightlen=strlen(right.Integer);
int maxlen=(leftlen>rightlen?leftlen:rightlen)+1;
MyInt t(maxlen+1);
if(left.Negative==right.Negative) //同号时情况
{
for (i=0;i<leftlen&&i<rightlen;++i) //改为&&
{
a=left.Integer[i]-'0'+right.Integer[i]-'0'+ j;
//t.Integer[i] = left.Integer[i]-'0'+right.Integer[i]-'0'+ j;你原来的没错,只是觉得改int更清晰一点.
j = a / 10;
t.Integer[i] = a % 10 + '0';
}
if(leftlen>rightlen)
for(;i<leftlen;i++)
{
a= left.Integer[i]-'0'+ j;
j = a / 10;
t.Integer[i] = a % 10 + '0';
}
if(leftlen<rightlen)
for(;i<rightlen;i++)
{
a= right.Integer[i]-'0'+ j;/
j = a/ 10;
t.Integer[i] = a % 10 + '0';
}
if(j){t.Integer[i]=j+48;t.Integer[i+1]=0;}
else t.Integer[i]=0;
if(left.Negative)t.Negative=true;//确定返回数的符号
} //至此同号的情况完.(加法情况)
return t;
}
//这个问题解决.至于减法,那是你自己算法的事了,你自己看着添吧.加法测试成功.
void main(int argc, char* argv[])
{
MyInt iM("12555"); // 整数对象初始化
MyInt iN("123555");
MyInt iResult1;
iResult1 =iN+iM;
iResult1.Display();
iResult1.freeInt(); //这样释放!!!!!
iM.freeInt();
iN.freeInt();
cout<<"~~~~~~~~~~~~~~ "<<endl;
}