返回的时候,如果局部变量是一个指针,返回的是局部变量的地址是会出错的。
因为返回的时候,这个局部变量已经消亡了,返回地址会是一片未知地址,造成麻烦。
解决办法:在函数中的局部变量前面加上static,成为静态变量。
具体例子:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int MAX = 110;
class CHugeInt {
int number[201];
public:
CHugeInt(int n) {
memset(number, 0, sizeof(number));
int pos = 200;
while ((n / 10) || (n % 10)) {
number[pos] = n % 10;
n /= 10;
pos--;
}
//cout << *this;
}
CHugeInt(const char* w) {
memset(number, 0, sizeof(number));
int pos = 200;
int posw = strlen(w) - 1;
for (int i = posw; i >= 0; i--) {
number[pos] = w[i] - '0';
pos--;
}
//cout << *this;
}
CHugeInt(const CHugeInt &a) {
for (int i = 200; i >= 0; i--) {
number[i] = a.number[i];
}
}
friend CHugeInt& operator+(const CHugeInt &nn, const CHugeInt &w) {
static CHugeInt sum(0);
int d = 0;
int pos = 200;
while (pos > 0) {
d = d + nn.number[pos] + w.number[pos];
sum.number[pos] = d % 10;
d /= 10;
pos--;
}
sum.number[pos] = d % 10;
return sum;
}
CHugeInt& operator+=(int n) {
CHugeInt nn(n);
int d = 0;
int pos = 200;
while (pos > 0) {
d = d + nn.number[pos] + number[pos];
number[pos] = d % 10;
d /= 10;
pos--;
}
number[pos] = d % 10;
return *this;
}
friend CHugeInt& operator+(CHugeInt& w,int n) {
CHugeInt nn(n);
static CHugeInt sum1(0);
int d = 0;
int pos = 200;
while (pos > 0) {
d = d + nn.number[pos] + w.number[pos];
sum1.number[pos] = d % 10;
d /= 10;
pos--;
}
sum1.number[pos] = d % 10;
return sum1;
}
friend CHugeInt& operator+(int n, CHugeInt& w) {
CHugeInt nn(n);
static CHugeInt sum2(0);
int d = 0;
int pos = 200;
while (pos > 0) {
d = d + nn.number[pos] + w.number[pos];
sum2.number[pos] = d % 10;
d /= 10;
pos--;
}
sum2.number[pos] = d % 10;
return sum2;
}
CHugeInt& operator++() {
int pos = 200;
number[pos] += 1;
while (pos > 0) {
number[pos - 1] += (number[pos] / 10);
number[pos] %= 10;
pos--;
}
return *this;
}
friend CHugeInt operator++(CHugeInt& w, int n) {
CHugeInt temp(w);
w += 1;
return temp;
}
friend ostream& operator <<(ostream& cout, CHugeInt w) {
int i0 = 0;
for (int i = 0;; i++) {
if (w.number[i]) {
i0 = i;
break;
}
if (i == 200) {
i0 = i;
break;
}
}
for (int i = i0; i <= 200; i++) {
cout << w.number[i];
}
return cout;
}
// 在此处补充你的代码
};
int main()
{
char s[210];
int n;
while (cin >> s >> n) {
CHugeInt a(s); ////constructor(用大整数) 需要重载
CHugeInt b(n);
cout << a + b << endl; ////重载+(两个对象)
cout << n + a << endl; ////重载+(对象和整数,满足交换律)
cout << a + n << endl;
b += n; ////重载+=
cout << ++b << endl; ////重载++i和i++
cout << b++ << endl; ////重载<<
cout << b << endl;
}
return 0;
}
在输出的时候,代码的a+b那一行在vs中输出了奇怪的东西,oj上是runtime error。在函数里面加cout答案是好的。返回的语句出了问题。当然我没在意那个warning,这样看起来re的线索可能在warning当中。在所有的sum前面加上了static并适当修改了变量名称就好了。