cpp operator = 未被调用使用类模板

问题描述

我如何定义类:

这就是我试图称呼它的方式

BSNode<std::string>* copy = new BSNode<std::string>("1");
copy->insert<std::string>("3");
BSNode<std::string>* copy2 = new BSNode<std::string>("2");
copy2 = copy;

但该函数根本没有被调用,它只是使用认的 =(浅拷贝)

h 文件(那只是 c'tors 和重载函数,我认为不重要):

template <class T>
class BSNode
{
public:
template <class T>
BSNode(T data)
{
    this->_data = data;
    this->_left = nullptr;
    this->_right = nullptr;
    this->_count = 1;
}
template <class T>
BSNode<T>& operator=(const BSNode<T>& other)
{
    this->_right = new BSNode<T>(other._right->_data);
    this->_left = new BSNode<T>(other._left->_data);
    this->_count = other._count;
    this->_data = other._data;

    return *this;
}

private:
T _data;
BSNode* _left;
BSNode* _right;

int _count; 

};

解决方法

此代码

copy2 = copy;

将一个指针复制到另一个指针。不可能为两个指针覆盖 operator=。如果您希望您的接线员被调用,请执行此操作

*copy2 = *copy;