代码段:(简化过的)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <stdlib.h>
#include <vector>
using namespace std;
/* 孩子兄弟链表的结点定义 */
template<class ElemType>
struct TreeNode
{
ElemType data;
int parent;
TreeNode<ElemType> *Child, *Sibling;
TreeNode() : Child(NULL), Sibling(NULL), parent(-1){} //构造函数1,用于构造根结点
};
//树ADT
template<class ElemType>
class Tree{
private:
TreeNode<ElemType> *root; // 头指针
void TreeDestroy_Cursive( TreeNode<ElemType> *T ); //销毁树(递归准备,private)
public:
//无参数的构造函数
Tree():root(NULL){}
//带参数的构造函数
Tree(const ElemType &item){root = new TreeNode<ElemType>(item);}
//生成树
void makeTree( const ElemType &item, Tree &child, Tree &sibling);
//销毁子树
void ChildDestroy(int flag);
//返回树结点的个数
int TreeSize() const{ return TreeSize(root);};
//判断树是否为空
bool TreeisEmpty() const{return root == NULL;}
};
int main(){
Tree<char>T();
cout<<T.TreeisEmpty();
}
语句:cout<<T.TreeisEmpty(); 报错。
报错原因:
因为无参的构造函数,如Tree<char>T();它可以是个对象,也可是函数声明。但是c++编译器总是优先认为是一个函数声明,然后是对象。
解决方法如下:
1. 不使用()直接初始化对象,比如Tree<char>T;
2. 使用花括号{}初始化对象,比如Tree<char>T{};