C++操作员过载?

C++ operator overload?

本文关键字:操作员 C++      更新时间:2023-10-16
class CHugeInt
{
private:
char buf[200];
public:
void reverse(char *p)
{
int i, j, len;
len = strlen(p), i = 0, j = len - 1;
while (i <= j)
{
swap(p[i], p[j]);
++i; 
--j;
}
}
CHugeInt(int n)
{
memset(buf, 0, sizeof(buf));
sprintf(buf, "%d", n);
reverse(buf);
}
CHugeInt operator + (int n)
{
return *this + CHugeInt(n);
}
CHugeInt operator + (const CHugeInt &n) const
{
int i, k, carry;
char c1, c2;
CHugeInt tmp(0);
carry = 0;
for (i = 0; i < 210; i++)
{
c1 = buf[i];
c2 = n.buf[i];
if (c1 == 0 && c2 == 0 && carry == 0)
{
break;
}
if (c1 == 0)
{
c1 = '0';
}
if (c2 == 0)
{
c2 = '0';
}
k = c1 - '0' + c2 - '0' + carry;
if (k >= 10)
{
carry = 1;
tmp.buf[i] = k - 10 + '0';
}
else
{
carry = 0;
tmp.buf[i] = k + '0';
}
}
return tmp;
}
friend CHugeInt operator + (int n, const CHugeInt &h)
{
return  h + n;
}
};
int main()
{
int n;
char s[210];
while (cin >> s >> n)
{
CHugeInt a(s), b(n);
cout << n + a << endl;
}
return 0;
}

cout << n + a << endl打电话给friend CHugeInt operator + (int n, const CHugeInt &h).

但是为什么return h + nCHugeInt operator + (const CHugeInt &n) const而不是CHugeInt operator + (int n)

如果删除函数friend CHugeInt operator + (int n, CHugeInt &h)参数中的常量,为什么它会调用CHugeInt operator + (int n)

问题是这个运算符

CHugeInt operator + (int n)
{
return *this + CHugeInt(n);
}

不是恒定的。因此,对于恒定对象,可能不需要调用它。

但在此声明中

cout << n + a << endl;

有叫算子

friend CHugeInt operator + (int n, const CHugeInt &h)
{
return  h + n;
}

其中第二个参数具有常量引用类型。

所以编译器使用转换构造函数

CHugeInt(int n)
{
memset(buf, 0, sizeof(buf));
sprintf(buf, "%d", n);
reverse(buf);
}

并调用接线员

CHugeInt operator + (const CHugeInt &n) const;

声明运算符像

CHugeInt operator + (int n) const
{
return *this + CHugeInt(n);
}