Mir*_*ina 0 c++ copy-constructor c++11
我在理解如何在C++中覆盖默认的复制构造函数时遇到问题.我没有收到任何编译错误.前面的例子向我展示了下面的模式.下面列出了文件HashTable.cpp和摘录Hashtable.h.
Hashtable.h
HashTable& operator=(const HashTable& other);`
Run Code Online (Sandbox Code Playgroud)
HashTable.cpp
const HashTable& HashTable::operator=(const HashTable& other) {
std::cout << "EQUAL OPERATOR METHOD" << std::endl;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
HashTable ht1 {9};
HashTable ht2 { ht1 };
Run Code Online (Sandbox Code Playgroud)
虽然在编译时,看起来好像没有调用复制构造函数.为了澄清,我试图将一个变量复制到另一个变量.
值得注意的是,我在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);
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
HashTable ht2(ht1);
Run Code Online (Sandbox Code Playgroud)
PS:不确定HashTable ht2 {ht1}(使用符号{和}).C++14根据MM的评论,这似乎是它的特色.
| 归档时间: |
|
| 查看次数: |
657 次 |
| 最近记录: |