微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么当我使用重载的赋值运算符时却出现错误,却没有使用编译器提供的运算符?

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

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

错误 从“ void”类型的返回值到函数返回类型“ BigInt”的可行转换 return res = a.BigInt::operator - (b);

解决方法

您的SELECT DISTINCT tt.ID,FIRST_VALUE(t) OVER W AS start FROM (SELECT t.*,ROW_NUMBER() OVER(ORDER BY t) - ROW_NUMBER() OVER(PARTITION BY ID ORDER BY t) AS rn FROM (SELECT ID,t FROM records) t) tt WINDOW W AS (PARTITION BY rn ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) ORDER BY start; +----+----------+ | id | start | +----+----------+ | 1 | 12:10:00 | | 2 | 14:18:05 | | 3 | 17:33:50 | | 1 | 20:03:14 | +----+----------+ 返回operator=,无法在void中返回,因为错误消息说return res = a.BigInt::operator - (b);应该返回operator +

您应该将BigInt声明为返回operator=(就像编译器生成的一样)。

BigInt&
,
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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。