出现这种情况表明:在类的构造函数中添加了默认参数;
但是如果想要给 构造函数添加默认参数,需要在类的公有接口中函数声明时添加默认参数。要在函数声明时给定默认参数。
#include <iostream>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::strlen;
using std::strcpy;
class baseMDA
{
private:
char *label;
int rateing;
public:
baseMDA(const char *l = "NULL", int r = 0); //构造
baseMDA(const baseMDA &); // 复制
baseMDA operator=(const baseMDA &); // 重载
friend std::ostream & operator<<(std::ostream &os, const baseMDA & bM);
virtual ~baseMDA();
};
baseMDA::baseMDA(const char *l, int r)
{
int len = sizeof(l)/sizeof(l[0]);
label = new char[len + 1]; // 嵌入strlen()函数节省空间
std::strncpy(label, l, len+1);
rateing = r;
}
baseMDA::baseMDA(const baseMDA & bM){
// 深度复制
label = new char[strlen(bM.label)+ 1];
strcpy(label, bM.label);
rateing = bM.rateing;
}
baseMDA baseMDA::operator=(const baseMDA &bM){
if (this == &bM)
return *this;
delete[] label;
label = new char[strlen(bM.label) + 1];
strcpy(label, bM.label);
rateing = bM.rateing;
return *this;
}
std::ostream & operator<<(std::ostream &os, const baseMDA & bM){
os<<"Label:"<<bM.label<<endl<<"Rateing:"<<bM.rateing<<endl;
return os;
}
baseMDA::~baseMDA()
{
delete[] label;
}
// lacksMDA
class lacksmda : public baseMDA
{
private:
enum{COL_LEN = 40};
char color[COL_LEN];
public:
lacksmda(const char *c = "NULL", const char* l = "NULL", int r = 0);
lacksmda(const char *c, baseMDA &bM);
friend std::ostream & operator<<(std::ostream &os, lacksmda & lm);
~lacksmda();
};
lacksmda::lacksmda(const char *c, const char* l, int r) : baseMDA(l, r)
{
strncpy(color, c, COL_LEN);
}
lacksmda::lacksmda(const char *c, baseMDA &bM) : baseMDA(bM){
strncpy(color, c, COL_LEN);
}
std::ostream & operator<<(std::ostream &os, lacksmda & lm){
os<< (baseMDA &) lm;
os<<"color:"<<lm.color<<endl;
return os;
}
lacksmda::~lacksmda()
{
}
class hasmda : public baseMDA
{
private:
char * style;
public:
hasmda(const char *st = "NULL", const char * la = "NULL", int r = 0);
hasmda(const char *st, baseMDA &);
hasmda(const hasmda &);
hasmda & operator=(const hasmda &);
friend std::ostream & operator<<(std::ostream & os, const hasmda &hM);
~hasmda();
};
hasmda::hasmda(const char *st, const char * la, int r) : baseMDA(la, r)
{
style = new char[strlen(st) + 1];
strcpy(style, st);
}
hasmda::hasmda(const char *st, baseMDA &bM) : baseMDA(bM){
style = new char[strlen(st) + 1];
strcpy(style, st);
}
hasmda::hasmda(const hasmda & hM) : baseMDA(hM){
style = new char[strlen(hM.style) + 1];
strcpy(style, hM.style);
}
hasmda & hasmda::operator=(const hasmda &hM){
if (this == &hM)
{
return *this;
}
baseMDA::operator=(hM); // 等号的左操作数调用基类的赋值运算符
delete[] style;
style = new char[strlen(hM.style) + 1];
strcpy(style, hM.style);
return *this;
}
std::ostream & operator<<(std::ostream & os, const hasmda &hM){
os<<(baseMDA &)hM;
os<<"style:"<< hM.style<<endl;
return os;
}
hasmda::~hasmda()
{
delete[] style;
}
int main(void)
{
baseMDA mda("name", 4);
lacksmda mda1("style1", mda);
cout<<mda<<endl<<mda1<<endl;
return 0;
}