模板化类常量限定符构造函数
Templated class const qualifier constructor
我无法通过"复制"已经存在的相同类型的对象来创建新对象。
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
指针。但是您的赋值运算符必须考虑到它可以作为左值调用默认构造值。
相关文章:
- constexpr构造函数需要常量成员函数时出现问题
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- C++ 常量正确性/缺少支持常量和非常量实例的类的常量构造函数
- 如何在使用 Qt5 构造函数时将非常量参数修改为常量参数?
- 通过从构造函数中的'this'复制的指针改变常量对象
- 为什么编译器在使用"无常量复制构造函数"时抱怨?
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- C++ 中常量属性的初始化构造函数错误
- 带有常量指针的矢量构造函数示例
- 调用构造函数与将内联常量定义为默认参数
- C++自动生成的具有常量和非常量引用的复制构造函数
- C++ 具有常量数组和initializer_list的重载构造函数
- 为什么在这种情况下调用非常量右值移动构造函数?
- 在可变参数构造函数中初始化常量数组
- 委派复制构造函数和常量数据初始化
- 为什么可以将左值传递到采用常量引用右值的构造函数中?
- CPP/C 中的常量用法和结构构造函数中的澄清
- 初始化类构造函数中的常量
- 与 map 一起使用时复制构造函数常量错误
- 提升::任何构造函数 - 常量类型重载分辨率