更改默认复制构造函数 C++

Changing the default copy constructor C++

我在理解如何覆盖 C++ 中的默认复制构造函数时遇到问题。我没有收到任何编译错误。前面的示例向我展示了下面的模式。下面列出了文件 HashTable.cppHashtable.h.

的摘录

Hashtable.h

HashTable& operator=(const HashTable& other);`

HashTable.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 问题。我花了很长时间试图弄清楚这里发生了什么,所以请不要投反对票。

HashTable::operator=(const HashTable& other) 是赋值运算符。复制构造函数应该写成HashTable::HashTable(const HashTable& other).

"HashTable ht2 { ht1 }" 不是在调用复制构造函数,它实际上是在调用 initializer_list: "HashTable(initializer_list<哈希表>)"

要调用复制构造函数你应该写 你的 main.cpp.

中的 HashTable hash(anotherHashTable)

您上面写的代码是 copy assignment operator, but, according to your main.cpp, seems like you need the copy constructor 的重写(不要被这些描述中的文字量吓到,它真的很容易理解)。试试下面的代码:

HashTable.h

class HashTable
{
private:
    // private members declaration...
public:
    // public members declaration...
    HashTable(const HashTable& other);
}

HashTable.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 功能

首先,你问题中的示例代码是一个copy assignment。拷贝构造函数与拷贝赋值的区别在于,拷贝构造函数只能在对象初始化时调用。在一个对象被初始化后,你想将另一个初始化的对象传递给它,复制赋值被调用。 所以在 main 函数中,由于 ht1 在初始化时被传递给 ht2,它宁愿调用复制构造函数。但是在您的代码中,您定义了复制赋值而不是复制构造函数。 查看 copy assignment c++ 以了解有关复制赋值和复制构造函数之间差异的更多详细信息。