[英]Changing the default copy constructor C++
我在理解如何覆盖C ++中的默认副本构造函数时遇到问题。 我没有收到任何编译错误。 前面的示例向我展示了我们的以下模式。 以下是文件HashTable.cpp
和Hashtable.h
摘录。
哈希表
HashTable& operator=(const HashTable& other);`
哈希表
const HashTable& HashTable::operator=(const HashTable& other) {
std::cout << "EQUAL OPERATOR METHOD" << std::endl;
return *this;
}
main.cpp
HashTable ht1 {9};
HashTable ht2 { ht1 };
尽管在编译时,好像没有调用复制构造函数。 为了澄清,我试图将一个变量复制到另一个变量。
值得注意的是,我正在Ubuntu 14.04上使用c ++ 11进行编码。 由于在Ubuntu中编写c ++对我来说已经有很多麻烦,所以我不确定这是c ++还是ubuntu问题。 我花了很多时间试图弄清楚这里发生了什么,所以请不要投反对票。
上面编写的代码是copy assignment operator
的重载,但是,根据main.cpp
看来,您似乎需要copy constructor
(不必担心这些描述中的文本数量,这很容易理解) 。 尝试以下代码:
哈希表
class HashTable
{
private:
// private members declaration...
public:
// public members declaration...
HashTable(const HashTable& other);
}
哈希表
// Copy constructor implementation
HashTable::Hashtable(const HashTable& other){
// implement your own copy constructor
std::cout << "OVERRIDED COPY CONSTRUCTOR METHOD" << std::endl;
// This is the constructor, so don't have to return anything
}
main.cpp
HashTable ht2(ht1);
PS:不确定HashTable ht2 {ht1}
(使用符号{
和}
)。 根据MM的评论,似乎是C++14
功能。
首先,问题中的示例代码是副本分配。 复制构造函数和复制分配之间的区别在于,复制构造只能在初始化对象时调用。 初始化对象后,您想将另一个初始化的对象传递给它,则将调用复制分配。 因此,在主函数中,因为在初始化ht2
时将ht1
传递给ht2
,所以它宁愿调用复制构造函数。 但是在您的代码中,您定义了副本分配,而不是副本构造函数。 请查看副本分配c ++,以获取有关副本分配和副本构造函数之间差异的更多详细信息。
HashTable :: operator =(const HashTable&other)是赋值运算符。 复制构造函数应写为HashTable :: HashTable(const HashTable&other)。
“ HashTable ht2 {ht1} ”没有调用复制构造函数,它实际上是在调用initializer_list:“ HashTable(initializer_list <HashTable>) ”
要调用复制构造函数,您应该在main.cpp中编写HashTable哈希(anotherHashTable) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.