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

时间:2015-12-09 04:06:13

标签: c++ c++11 copy-constructor

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

3 个答案:

答案 0 :(得分:5)

您上面写的代码是copy assignment operator的覆盖,但根据您的main.cpp,您似乎需要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功能。

答案 1 :(得分:2)

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

答案 2 :(得分:1)

HashTable :: operator =(const HashTable&amp; other)是赋值操作符。复制构造函数应该写成HashTable :: HashTable(const HashTable&amp; other)。

&#34; HashTable ht2 {ht1} &#34;它没有调用copy-constructor,它实际上正在调用initializer_list:&#34; HashTable(initializer_list&lt; HashTable&gt;)&#34;

要调用复制构造函数,您应该编写 main.cpp中的 HashTable哈希(anotherHashTable)