class Port
{
private:
char*brand;
char style[20];
int bottles;
public:
Port(const char*br = "none", int b = 0,const char *st = "none");
Port(const Port&p);
virtual~Port(){ delete[]brand; };
Port&operator=(const Port&p);
Port&operator+=(int b);
Port&operator-=(int b);
int BottleCount()const{ return bottles; };
virtual void Show()const;
friend ostream &operator<<(ostream&os, const Port &p);
};
class VintagePort :public Port
{
private:
char *nickname;
int year;
public:
VintagePort();
VintagePort(const char*br, int b, const char*nn, int y);
VintagePort(const VintagePort &vp);
~VintagePort(){ delete[]nickname; };
VintagePort &operator=(const VintagePort &vp);//容易混淆,没有实际意义
void Show()const;//虚函数在派生类重新定义
friend ostream&operator<<(ostream &os, const VintagePort &vp);//友元函数不能为虚
};
Port::Port(const char*br, int b,const char *st)
{
brand = new char[strlen(br) + 1];
strcpy(brand, br);
strcpy_s(style, st);
bottles = b;
}
Port::Port(const Port&p)
{
brand = new char[strlen(p.brand) + 1];
strcpy(brand, p.brand);
strcpy_s(style, p.style);
bottles = p.bottles;
}
Port&Port::operator = (const Port&p)
{
if (this == &p)
{
return *this;
}
delete[]brand;
brand = new char[strlen(p.brand) + 1];
strcpy(brand, p.brand);
strcpy_s(style, p.style);
bottles = p.bottles;
}
Port&Port::operator += (int b)
{
bottles += b;
return *this ;
}
Port&Port::operator -= (int b)
{
bottles -= b;
return *this;
}
void Port::Show()const
{
cout << "Brand: " << brand << endl;
cout << "Kind: " << style << endl;
cout << "Botle: " << bottles << endl;
}
ostream &operator<<(ostream&os, const Port &p)
{
os << p.brand << ", " << p.style << ", " << p.bottles << ", \n";
return os;
}
VintagePort::VintagePort() :Port()
{
nickname = 0;
year = 0;
}
VintagePort::VintagePort(const char*br, int b, const char*nn, int y) : Port(br, b)
{
nickname = new char[strlen(nn) + 1];
strcpy(nickname, nn);
year = y;
}
VintagePort::VintagePort(const VintagePort &vp) :Port(vp)
{
nickname = new char[strlen(vp.nickname) + 1];
strcpy(nickname, vp.nickname);
year = vp.year;
}
VintagePort &VintagePort::operator = (const VintagePort &vp)
{
if (this == &vp)
{
return *this;
}
Port::operator=(vp);
nickname = new char[strlen(vp.nickname) + 1];
strcpy(nickname, vp.nickname);
year = vp.year;
return *this;
}
void VintagePort::Show()const
{
Port::Show();
cout << "nickname: " << nickname << endl;
cout << "year: " << year << endl;
}
ostream&operator<<(ostream &os, const VintagePort &vp)
{
operator<<(cout,(Port)vp);
cout << ", ";
cout << vp.nickname << ", " << vp.year << "\n";
return os;
}
|