重载的复制构造函数似乎没有被调用

Overloaded copy constructor doesn't seem to be called

本文关键字:调用 复制 构造函数 重载      更新时间:2023-10-16

我是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);