当前位置: 代码迷 >> 综合 >> C++中关于std::pair<const K,V>的初始化问题
  详细解决方案

C++中关于std::pair<const K,V>的初始化问题

热度:52   发布时间:2023-10-25 08:12:10.0

如题所见,在类中如果有一个成员是std::pair<const K,V>这种类型的话,那么在初始化这个成员的时候,一定要注意在构造函数中使用初始化的方式去给它初始化,而不是在大括号中进行赋值!!

template<typename T>
struct binaryTreeNode{
    T element;binaryTreeNode<T> *leftChild,       //左子树*rightChild;      //右子树binaryTreeNode(){
    leftChild = rightChild = NULL;}binaryTreeNode(const T& theElement):element(theElement){
    leftChild = rightChild = NULL;}binaryTreeNode(const T &theElement,binaryTreeNode *theLeftChild,binaryTreeNode *theRightChild):element(theElement){
    //注意,类型中出现了const的,一定要利用初始化,而不是赋值的方式去给他们leftChild = theLeftChild;rightChild = theRightChild;}
};
假设现在binaryTreeNode<std::pair<const K,V>> *s = p->leftChild;//这个leftChild也是一个指针
那么我现在使用这个函数的时候binaryTreeNode<std::pair<const K,V>> *q = new binaryTreeNode<std::pair<const K,V>>(s->element,p->leftChild,p->rightChild);
会报错:/usr/include/c++/5/bits/stl_pair.h: In instantiation of ‘std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = char]:
binaryTreeNode.h:20:17:   required from ‘binaryTreeNode<T>::binaryTreeNode(const T&, binaryTreeNode<T>*, binaryTreeNode<T>*) [with T = std::pair<const int, char>]’
binarySearchTree.h:91:91:   required from ‘void binarySearchTree<K, V>::erase(const K&) [with K = int; V = char]’
binarySearchTree.cpp:21:14:   required from here
/usr/include/c++/5/bits/stl_pair.h:160:8: error: assignment of read-only member ‘std::pair<const int, char>::first’first = __p.first;
其实我们仔细看,发现报错的内容是我们的const关键字在赋值的时候被改变了。为什么被改变了就会报错?我们再来看看,
我们定义的std::pair<const K,V>第一个参数是const类型的,所以在赋值的时候,会发生改变const类型变量的问题。
那么我最后追踪发现,赋值的情况基本上发生在了构造函数最开始的时候。我发现我最开始使用的是如下的构造函数:binaryTreeNode(const T &theElement,binaryTreeNode *theLeftChild,binaryTreeNode *theRightChild){
    //注意,类型中出现了const的,一定要利用初始化,而不是赋值的方式去给他们element = theElement;//有可能是const类型,不要在大括号中进行赋值leftChild = theLeftChild;rightChild = theRightChild;}
我在构造函数大括号中使用了element=theElement去赋值了。所以肯定会发生T作为std::pair<const K,V>的时候,
发生上述的问题。所以为了解决上述问题,我们只需要把element = theElement;
在构造函数中直接放到:后边进行初始化就好了!!!所以记住一点:
如果你的类的成员的类型如果有可能是const类型的,那么一定要使用初始化的方式去初始化该变量,而不要先使用默认初始化的方式,然后再去赋值的方法(在构造函数中使用=去赋值)!!!
  相关解决方案