template<class ElemType>
struct Node
{
ElemType data;
Node<ElemType> *next;
Node();
Node(ElemType Item);
Node(ElemType Item,Node<ElemType> *link=NULL);
};
template<class ElemType>
Node<ElemType>::Node()
{
next=NULL;
}
template<class ElemType>
Node<ElemType>::Node(ElemType Item)
{
data=Item;
next=NULL;
}
template<class ElemType>
Node<ElemType>::Node(ElemType Item,Node<ElemType> *link)
{
data=Item;
next=link;
}
1.
如果自己这样定义Node<int> a(3);则会出现错误,事实上,编译器并不知道是第二个构造函数还是第三个构造函数,因为第三个构造函数中第二个参数是有默认值的。
2.
如果针对带有默认值的成员函数,=NULL必须要在结构体内声明,如果同时在下面的实现中也添加上=NULL或仅仅在实现中添加上=NULL,编译器都会报错。
#include <string.h>
class My_String
{
protected:
char *strVal;
int length;
public:
My_String();
virtual ~My_String();
My_String(const My_String ©);
My_String(const char *copy);
//String(LinkList<char>©);
int Length() const;
bool Empty() const;
My_String &operator=(const My_String ©);
My_String &operator=(const char *copy);
const char *CStr() const;//把串转换成C风格串
//const char &My_String::operator[](int i) const;
};
/*
My_String Read(istream &input);
My_String Read(istream &input,char &terminalChar);
void Write(const My_String &s);
void Concat(My_String &addTo,const My_String &addOn);
void Copy(My_String ©,const My_String &original);
void Copy(My_String ©,const My_String &original,int n);
int Index(const My_String &target,const My_String &pattern,int pos=0);
My_String SubString(const My_String &first,const My_String &second);
bool operator==(const My_String &first,const My_String &second);
bool operator<(const My_String &first,const My_String &second);
bool operator>(const My_String &first,const My_String &second);
bool operator<=(const My_String &first,const My_String &second);
bool operator>=(const My_String &first,const My_String &second);
bool operator==(const My_String &first,const My_String &second);
*/
My_String::My_String()
{
length=strlen("");
strVal=new char[length+1];
strcpy(strVal,"");
}
My_String::My_String(const char *inString)
{
length=strlen(inString);
strVal=new char[length+1];
strcpy(strVal,inString);
}
My_String::~My_String()
{
}
const char* My_String::CStr() const
{
return(const char*)strVal;
}
My_String &My_String::operator=(const char *copy)
{
if(copy!=NULL)
{
delete []strVal;
length=strlen(copy);
strVal=new char[length+1];
strcpy(strVal,copy);
}
return *this;
}
My_String &My_String::operator=(const My_String ©)
{
if(©!=this)
{
delete []strVal;
length=strlen(copy.CStr());
strVal=new char[length+1];
strcpy(strVal,copy.CStr());
}
return *this;
}
3.如果定义
My_String str;
那么str="some string.";cout<<My_String.CStr()<<endl;
如果重载=运算符只有第二种,那么会将"some string."认为是My_String一个实例的地址,必然出现错误。如果两种类型都有,则编译器自动匹配第一种。
如果重载运算符都没有实现,那么会编译错误吗?
4.并不会编译错误!
此时对声明的对象进行赋值,编译器会自动寻找与当前匹配的构造函数。此时,上图红色语句会调用My_String::My_String(const char *inString)的构造函数。那么,如果此构造函数不存在呢?
5.编译错误