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

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

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

相关文章:

c++ - 使用 Eclipse 构建 c++0x 特性

c++ - 创建新线程时复制构造函数调用

c++ - 在此函数中使用引用参数有什么好处吗?

c++ - 从 MATLAB 调用静态库中的 C++ 类成员函数

c++ - 创建此功能模板

c++ - C++ 中的 ruby​​ `Object#freeze` 通讯器是什么?

c++ - 包装 std::ignore

c++ - 在私有(private)类语法中复制构造函数

c++ - 作为 COM 接口(interface)一部分的默认参数

c++ - 将类方法设置为外部定义的函数