[英]C++ Default Templated Constructor With 1 Parameter
我正在嘗試創建在BinarySearchTree中使用的BinaryNode類。 當我嘗試測試此代碼並運行下面的程序時,它沒有任何錯誤地進行編譯,但是在運行該程序時,它停止並返回:分段錯誤(核心已轉儲)
誰能看到我的錯誤?
#ifndef _NODE
#define _NODE
#include <string>
#include <iostream>
using namespace std;
template<class ItemType>
class BinaryNode
{
private:
ItemType item; //any data type
BinaryNode<ItemType>* leftChild;
BinaryNode<ItemType>* rightChild;
public:
BinaryNode();
BinaryNode( ItemType newItem );
void setItem(ItemType newData);
ItemType getData() { return item;}
BinaryNode<ItemType>* getLeftChild() { return leftChild; }
BinaryNode<ItemType>* getRightChild() { return rightChild; }
void setLeftChild(BinaryNode<ItemType>* newLeftPtr) { leftChild = newLeftPtr;}
void setRightChild(BinaryNode<ItemType>* newRightPtr) { rightChild = newRightPtr;}
//void display(BinaryNode* rootNode);
};
template<class ItemType>
BinaryNode<ItemType>::BinaryNode()
{
BinaryNode newNode;
newNode.setItem( NULL );
newNode.setLeftChild( nullptr);
newNode.setRightChild( nullptr );
}
template<class ItemType>
BinaryNode<ItemType>::BinaryNode(ItemType newItem)
{
BinaryNode newNode;
newNode.setItem( newItem );
newNode.setLeftChild( nullptr );
newNode.setRightChild( nullptr );
}
template<class ItemType>
void BinaryNode<ItemType>::setItem(ItemType newData)
{
item = newData;
}
#endif
******************* MAIN *************************************
#include<iostream>
#include <string>
#include "BinaryNode.h"
using namespace std;
int main()
{
BinaryNode<string> newNode("string");
cout << newNode.getData() << endl;
return 0;
}
********************** ERROR ***************************
Segmentation fault (core dumped)
問題實際上很簡單:
template<class ItemType>
BinaryNode<ItemType>::BinaryNode(ItemType newItem)
{
BinaryNode newNode;
newNode.setItem( newItem );
newNode.setLeftChild( nullptr );
newNode.setRightChild( nullptr );
}
在采用ItemType
構造函數中,您將創建一個局部變量newNode
。 在此作用域的末尾,將調用該對象的析構函數,因此它不再存在。
編輯:但是,您得到分段錯誤的原因是由於opetroch帖子中解釋的無限遞歸:
您的構造函數將通過進行無限遞歸導致堆棧溢出。
BinaryNode :: BinaryNode(ItemType newItem)創建一個本地變量,將為其調用默認構造函數,而該本地變量又將創建另一個本地變量,將再次為其調用默認構造函數,一直進行到堆棧溢出為止。
構造函數應改為:
template<class ItemType>
BinaryNode<ItemType>::BinaryNode(ItemType newItem)
{
setItem( newItem );
setLeftChild( nullptr );
setRightChild( nullptr );
}
因為隱式的“ this”指針傳遞給構造函數和所有其他成員函數,所以指向該函數被調用的對象。 這是您需要修改以獲得所需行為的對象。 您甚至可以通過如下編寫構造函數來使其真正顯式:
template<class ItemType>
BinaryNode<ItemType>::BinaryNode(ItemType newItem)
{
this->setItem( newItem );
this->setLeftChild( nullptr );
this->setRightChild( nullptr );
}
您的構造函數將通過進行無限遞歸導致堆棧溢出。
BinaryNode :: BinaryNode(ItemType newItem)創建一個本地變量,將為其調用默認構造函數,而該本地變量又將創建另一個本地變量,將再次為其調用默認構造函數,一直進行到堆棧溢出為止。
您應該根據Himmel的Glühwürmchen的職位更改構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.