gpt4 book ai didi

C++ 运算符重载?

转载 作者:行者123 更新时间:2023-11-28 04:04:52 27 4
gpt4 key购买 nike

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 + n电话 CHugeInt operator + (const CHugeInt &n) const而不是 CHugeInt operator + (int n)

为什么调用 CHugeInt operator + (int n)如果函数参数中的 const friend CHugeInt operator + (int n, CHugeInt &h)被移除了?

最佳答案

问题是这个运算符

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

不是常数。因此可能不会为 constnat 对象调用它。

但是在这个声明中

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);
}

关于C++ 运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58912369/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com