0 c++ boolean overloading this operator-keyword
为什么bool
要调用演员表?
Set result(*this)
调用构造函数时出现问题。我希望它使用拷贝构造函数,而不是它转换*this
到bool
并使用它作为一个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)
复制构造函数的参数Set::Set(Set& copied)
不是const
引用。运营商Set Set::operator+(const Set& rhs)const
是const
如此this
是const Set *
和*this
是const Set
。由于您不能将a传递const T
给T&
参数(它将丢弃const
),因此您可能无法在此上下文中使用复制构造函数。
要解决此问题,请const Set &
改为让您的副本构造函数接受,就像copy
member函数一样:
Set::Set(const Set& copied)
// ^^^^^ Added const here
{
copy(copied);
}
Run Code Online (Sandbox Code Playgroud)
编辑:强制性的免责声明,您不必编写自己的动态大小的数组。使用std::vector
代替。这将大大简化您的类型,并且可能会更加安全。
归档时间: |
|
查看次数: |
88 次 |
最近记录: |