error C2648: “MyDoublyLinkedlist::length”: 將成員作爲默認參數使用要求靜態成員

C++中只能將靜態成員設置爲默認參數,默認參數不能是一個普通變量。


代碼如下(insert函數有誤):

#pragma once
#include<iostream>

template<typename Element> 
class MyDoublyLinkedlistNode;

template<typename Element>
class MyDoublyLinkedlist;



template<typename Element>
class MyDoublyLinkedlistNode
{
	template<typename X> friend class MyDoublyLinkedlist;
public:
	MyDoublyLinkedlistNode(Element nodeValue) :nodeValue(nodeValue){}

private:
	Element nodeValue;
	MyDoublyLinkedlistNode<Element>* prev = nullptr,* next = nullptr;
};

template<typename Element> 
class MyDoublyLinkedlist
{	
public:
	MyDoublyLinkedlist():header(nullptr){};
	MyDoublyLinkedlist(Element firstNodeValue) 
		:header(new MyDoublyLinkedlistNode<Element>(firstNodeValue)),length(1){}

	bool isEmpty(){ return header == nullptr; }
	MyDoublyLinkedlistNode<Element>* searchByValue(Element searchValue)
	{
		MyDoublyLinkedlistNode<Element>* tmpPoint = header;

			while (tmpPoint != nullptr)
			{
				if (tmpPoint->nodeValue == searchValue)
					break;
				else
					tmpPoint = tmpPoint->next;
			}
		return tmpPoint;
	}

	MyDoublyLinkedlistNode<Element>* insert(Element insertValue, size_t index=length)//insert back 
	{
		if (index > length)
			index = length;
		MyDoublyLinkedlistNode<Element>* tmpPoint = header;
		while (index != 0)
		{
			tmpPoint = tmpPoint->next;
		}
		MyDoublyLinkedlistNode<Element>* trans = tmpPoint->next;
		tmpPoint->next = new MyDoublyLinkedlistNode<Element>(insertValue);
		tmpPoint->next->next = trans;
		if (trans != nullptr)
		{
			trans->prev = tmpPoint->next;
		}
		if (tmpPoint != header)
		{
			tmpPoint->next->prev = tmpPoint;
		}
		++length;
	}
	


	void print()
	{
		MyDoublyLinkedlistNode<Element>* tmpPoint = header;
		while (!(tmpPoint == nullptr))
		{
			std::cout << tmpPoint->nodeValue << " ";
			tmpPoint = tmpPoint->next;
		}
		std::cout << std::endl;
	}

private:
	MyDoublyLinkedlistNode<Element>* header = nullptr;
	size_t length = 0;
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章