重载的复制构造函数似乎没有被调用
Overloaded copy constructor doesn't seem to be called
我是C++的新手,我正试图重载HashingTable类的复制构造函数。我已经找了好几个小时了,但似乎不明白为什么它没有被调用。我使用的是MVS 2015。相关代码:
class HashingTable
{
...
public:
/*
* Constructors
*/
// Default constructor
HashingTable();
// Default destructor
virtual ~HashingTable();
// Constructor requiring size of vector to create
HashingTable(int size);
// Copy constructor requiring another instance of HashingTable
explicit HashingTable(const HashingTable& ht);
}
// Copy constructor using another table instance
template <class obj_type>
HashingTable<obj_type>::HashingTable(const HashingTable& ht)
{
cout << "Copy constructor called" << endl;
*this = ht;
}
// Overload of operator=
template <class obj_type>
HashingTable<obj_type>& HashingTable<obj_type>::operator=(constHashingTable& ht)
{
cout << "In operator=..."
if (this != &ht) // no need to copy itself
{
// do some stuff to *this
}
return *this;
}
在主((中
HashingTable<char*>* table2(myHashTable);
永远看不到"Copy constructor called"或"In operator=…"的输出。
myHashTable
属于HashingTable<char*>*
类型。这里重要的是它是一个指针,而不是一个对象。
table2
是也是HashingTable<char*>*
,因此当执行HashingTable<char*>* table2(myHashTable);
时,指针值正在被复制,HashingTable
的实际复制构造函数被从不调用。
您必须复制一个HashingTable
对象才能调用您声明的构造函数,即
HashingTable<char*> notAPointerHashTable(*myHashTable);
相关文章:
- 当从函数参数中的临时值调用复制构造函数时
- 为什么调用复制构造函数而不是移动构造函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 编译器调用复制运算符而不是移动运算符
- push_back std::vector,则重复调用复制构造函数
- 为什么调用复制构造函数来构造空unique_ptr向量?
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 我打算调用initializer_list构造函数,如果存在,则事先调用复制构造函数:为什么?
- C++ - 从移动分配运算符调用复制分配
- 构造函数初始值设定项列表未调用复制构造函数
- 为什么在我的代码中调用复制构造函数而不是移动构造函数?
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- 通过引用传递对象时是否调用复制构造函数?
- 如果函数按值传递并按值返回,将调用复制构造函数多少次
- 为什么要抛出引用调用复制构造函数的异常?
- 为什么即使参数标记为"const",也会调用复制构造函数?
- Clang-Tidy:移动构造函数通过调用复制构造函数来初始化类成员
- 为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
- 为什么调用复制构造函数,当我只返回对象 c++ 的引用时
- 为什么在下面的代码中调用复制构造函数两次