模板化类常量限定符构造函数

Templated class const qualifier constructor

本文关键字:构造函数 常量      更新时间:2023-10-16

我无法通过"复制"已经存在的相同类型的对象来创建新对象。

template<class dataType>
inline Node<dataType>::Node(const Node<dataType> & node)
{
    if (this != nullptr)
    {
        this->mData = node.getData();
        this->mLeft = node.getLeft();
        this->mRight = node.getRight();
    }
}

我应该使用上述方法吗?或者我应该只做:

template<class dataType>
    inline Node<dataType>::Node(const Node<dataType> & node)
    {
        this = node;
    }

后者产生下一个错误:

1>h:projectsbinary search treesdataclassesnode.h(51): error C2440: '=': cannot convert from 'const Node<float> *' to 'Node<float> *const '
1>  h:projectsbinary search treesdataclassesnode.h(51): note: Conversion loses qualifiers

前者抱怨类似的事情:

1>h:projectsbinary search treesdataclassesnode.h(51): error C2662: 'float Node<float>::getData(void)': cannot convert 'this' pointer from 'const Node<float>' to 'Node<float> &'
1>  h:projectsbinary search treesdataclassesnode.h(51): note: Conversion loses qualifiers

我做错了什么?

如果你已经在某处定义了赋值运算符,你可以使用

template<class dataType>
    inline Node<dataType>::Node(const Node<dataType> & node)
    {
        *this = node;
    }

重用其代码,不要重复自己。*表示取消引用this指针。但是您的赋值运算符必须考虑到它可以作为左值调用默认构造值。