为什么叫布尔铸造?

0 c++ boolean overloading this operator-keyword

为什么bool要调用演员表?

Set result(*this)调用构造函数时出现问题。我希望它使用拷贝构造函数,而不是它转换*thisbool并使用它作为一个int的构造函数。

如何修复它以使用复制构造函数?

Set Set::operator+(const Set& rhs)const
{
    Set result(*this);

    for (unsigned int i = 0; i < rhs.getSize(); i++)
    {
        result.add(rhs[i]);
    }
    return result;
}

Set::operator bool()const
{
    return !!(*this);
}

Set::Set(size_t capacity)
{
    data = new int[capacity];
    size = 0;
    this->capacity = capacity;
}

void Set::copy(const Set& copied)
{
    size = copied.getSize();
    capacity = copied.getCapacity();
    if (data != nullptr)
        delete[]data;
    data = new int[capacity];
    for (unsigned int i = 0; i < size; i++)
        data[i] = copied.getAt(i);
}

Set::Set(Set& copied)
{
    copy(copied);
}

Set& Set::operator=(const Set& copied)
{
    if (this != &copied)
        copy(copied);
    return *this;
}

int& Set::getAt(unsigned int idx)const
{
    if (idx < 0 || idx >= size)
        throw "Invalid index\n";

    return data[idx];
}

bool Set::operator !()const
{
    if (size == 0)
        return true;
    return false;
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*eux 5

复制构造函数的参数Set::Set(Set& copied)不是const引用。运营商Set Set::operator+(const Set& rhs)constconst如此thisconst Set **thisconst Set。由于您不能将a传递const TT&参数(它将丢弃const),因此您可能无法在此上下文中使用复制构造函数。

要解决此问题,请const Set &改为让您的副本构造函数接受,就像copymember函数一样:

Set::Set(const Set& copied)
//       ^^^^^ Added const here
{
    copy(copied);
}
Run Code Online (Sandbox Code Playgroud)

编辑:强制性的免责声明,您不必编写自己的动态大小的数组。使用std::vector代替。这将大大简化您的类型,并且可能会更加安全。

  • @DianIvanov假设您不能将`std :: vector &lt;int&gt;`用于`data`。如果可以,请使用`vector`。这将使您在这里所做的一切都变得更容易,更容易。 (2认同)