我在理解如何覆盖 C++ 中的默认复制构造函数时遇到问题。我没有收到任何编译错误。前面的示例向我展示了下面的模式。下面列出了文件 HashTable.cpp
和 Hashtable.h
的摘录。
Hashtable.h
HashTable& operator=(const HashTable& other);`
哈希表.cpp
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
(不要被这些描述中的文字量吓到,它真的很容易理解)。试试下面的代码:
HashTable.h
class HashTable
{
private:
// private members declaration...
public:
// public members declaration...
HashTable(const HashTable& other);
}
哈希表.cpp
// 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}
(使用符号 {
和 }
)。根据 M.M 的评论,这似乎是 C++14
的特性。
关于c++ - 更改默认复制构造函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34170535/