模板化 class const 限定符构造函数
Templated class const qualifier constructor
我无法通过 "copying" 已存在的相同类型的对象创建新对象。
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:\projects\binary search trees\data\classes\node.h(51): error C2440: '=': cannot convert from 'const Node<float> *' to 'Node<float> *const '
1> h:\projects\binary search trees\data\classes\node.h(51): note: Conversion loses qualifiers
前者抱怨类似的事情:
1>h:\projects\binary search trees\data\classes\node.h(51): error C2662: 'float Node<float>::getData(void)': cannot convert 'this' pointer from 'const Node<float>' to 'Node<float> &'
1> h:\projects\binary search trees\data\classes\node.h(51): note: Conversion loses qualifiers
我做错了什么?
如果你在某处已经定义了赋值运算符,你可以使用
template<class dataType>
inline Node<dataType>::Node(const Node<dataType> & node)
{
*this = node;
}
重用它的代码,不要重复自己。
*
表示取消引用 this
指针。但是你的赋值运算符必须考虑到它可以被调用作为左值的默认构造值。
我无法通过 "copying" 已存在的相同类型的对象创建新对象。
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:\projects\binary search trees\data\classes\node.h(51): error C2440: '=': cannot convert from 'const Node<float> *' to 'Node<float> *const '
1> h:\projects\binary search trees\data\classes\node.h(51): note: Conversion loses qualifiers
前者抱怨类似的事情:
1>h:\projects\binary search trees\data\classes\node.h(51): error C2662: 'float Node<float>::getData(void)': cannot convert 'this' pointer from 'const Node<float>' to 'Node<float> &'
1> h:\projects\binary search trees\data\classes\node.h(51): note: Conversion loses qualifiers
我做错了什么?
如果你在某处已经定义了赋值运算符,你可以使用
template<class dataType>
inline Node<dataType>::Node(const Node<dataType> & node)
{
*this = node;
}
重用它的代码,不要重复自己。
*
表示取消引用 this
指针。但是你的赋值运算符必须考虑到它可以被调用作为左值的默认构造值。