为什么我在使用重载赋值运算符时会出错,但我却没有使用编译器提供的运算符?

Why do I get errors when I use the overloaded assignment operator, but I don't get using the compiler-supplied one?

我尽量只放最重要的部分:

header.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 return res = a.BigInt::operator - (b); 时出现错误,但当我 return 时却没有,它是这样的:res = a.BigInt::operator - (b); return res;。但这只会在我重载 = 运算符时发生,编译器提供的运算符不会发生。

错误: 无法从 return 类型 'void' 的值转换为函数 return 类型 'BigInt'return res = a.BigInt::operator - (b);

您的 operator= returns void,无法 returned in return res = a.BigInt::operator - (b);,如错误消息所述,operator + 应该 return a BigInt.

您应该将 operator= 声明为 returning BigInt&(正如编译器生成的那样)。

BigInt& BigInt::operator = (const BigInt &p)
{
    (*this).vec = p.vec;
    (*this).neg = p.neg;
    return *this;
}
void BigInt::operator = (const BigInt &p)

我觉得不对(void return)。分配的结果应该是分配的值,这就是允许您执行以下操作的原因:

a = b = 7

或者,在这种情况下更重要的是:

return res = ...

你赋值的变量的operator=大概应该是returnBigInt&,比如:

BigInt &BigInt::operator=(const BigInt &p) {
    this->vec = p.vec;
    this->neg = p.neg;
    return *this;
}