![](/img/trans.png)
[英]Why do I get a SIGSEGV when I use my overloaded insertopm (<<) operator?
[英]Why do I get errors when I use the overloaded assignment operator, but I don't get using the compiler-supplied one?
我尽量只放最重要的部分:
头文件.h
#include <cstdint>
#include <string>
#include <vector>
#include "byte.h" /// doesn't matter what's in here
#pragma once
using int64 = int64_t;
using int32 = int32_t;
/// FORWARD-DECLARATIONS
class BigInt;
/// *** CLASS BIGINT ***
class BigInt
{
std::vector<byte> vec;
bool neg; /// true if negative
public:
/// CONSTRUCTORS
BigInt ();
BigInt (const int64);
/// OPERATORS
/// ASSIGNMENT
void operator = (const BigInt&);
/// ARITHMETIC
BigInt operator + (const BigInt&);
BigInt operator - (const BigInt&);
};
/// DEFINITIONS
/// CONSTRUCTORS
BigInt::BigInt () : vec(1), neg(0) {}
BigInt::BigInt (const int64 x) : vec(x), neg(0) {}
/// OPERATORS
/// ASSIGNMENT
void BigInt::operator = (const BigInt &p)
{
(*this).vec = p.vec;
(*this).neg = p.neg;
}
/// ARITHMETIC
BigInt BigInt::operator + (const BigInt &p)
{
BigInt a = *this;
BigInt b = p;
BigInt res;
if (a.neg ^ b.neg)
{
if (a.neg)
std::swap(a, b);
b.neg = 0;
/*return*/ res = a.BigInt::operator - (b); /// I get an error if I don't comment this out
return res;
}
return res;
}
BigInt BigInt::operator - (const BigInt &p)
{
BigInt a = *this;
BigInt b = p;
BigInt res;
return res;
}
在BigInt BigInt::operator + (const BigInt &p)
当我尝试返回时出现错误return res = a.BigInt::operator - (b);
,但不是当我像这样返回它时: res = a.BigInt::operator - (b); return res;
res = a.BigInt::operator - (b); return res;
. 但这仅在我重载=
运算符时发生,编译器提供的运算符不会发生这种情况。
错误:没有从“void”类型的返回值到函数返回类型“BigInt”的可行转换return res = a.BigInt::operator - (b);
您的operator=
返回void
,不能在return res = a.BigInt::operator - (b);
中return res = a.BigInt::operator - (b);
,正如错误消息所说, operator +
应该返回一个BigInt
。
您应该将operator=
声明为返回BigInt&
(就像编译器生成的那样)。
BigInt& BigInt::operator = (const BigInt &p)
{
(*this).vec = p.vec;
(*this).neg = p.neg;
return *this;
}
void BigInt::operator = (const BigInt &p)
我认为这是不对的( void
返回)。 分配的结果应该是分配的值,这允许您执行以下操作:
a = b = 7
或者,在这种情况下更重要的是:
return res = ...
operator=
可能应该返回您将值放入的变量的BigInt&
,例如:
BigInt &BigInt::operator=(const BigInt &p) {
this->vec = p.vec;
this->neg = p.neg;
return *this;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.