C++操作员过载?
C++ operator overload?
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)
?
如果删除函数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);
}
相关文章:
- <<操作员在下面的行中工作
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 比根<操作员
- SFINAE不能防止模棱两可的操作员过载吗?
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- 为什么"delete"操作员给我访问权限冲突
- 为什么使操作员成为新的专用会打破 std::shared_ptr?
- 在这种情况下是私有的吗?试图使操作员<<过载
- C++操作员过载>>
- 是否有 C++20 浮点数的包装器,使我能够默认宇宙飞船操作员?
- 与异常处理程序中的操作员<<不匹配
- 复印作业操作员说明
- 友谊和操作员+=重载
- >操作员在比较两个C++容器时会怎么做?
- 与操作员比较两个计时时间点
- C++操作员订单评估
- 如何强制新操作员根据我的需要解释语句