您的位置:首页 > 编程语言 > C语言/C++

chapter13test4

2015-06-18 09:43 351 查看
后边三个问题我没有答,跟前面复习题的解答差不多,可以看看书后边的答案。下面是一个可以运行的程序。

port.h

#ifndef PORT_H_

#define PORT_H_

using namespace std;

#include<iostream>

class port

{

private:
char *brand;
char style[20];
int bottle;

public:
port(const char *b = "none", const char *s = "none", int bo = 0);
port(const port &p);
virtual ~port() { delete[]brand; }
port &operator=(const port &p);
port &operator +=(int bo);
port &operator -=(int bo);
int Bottle()const { return bottle; }
virtual void show() const;
friend ostream &operator<<(ostream &os, const port &p);

};
class vintage:public port
{
private:
char *nickname;
int year;
public:
vintage();
vintage(const char *n, int y, char *b, char *s, int bo);
vintage(const vintage &v);
~vintage(){ delete[]nickname; }
vintage &operator=(const vintage &v);
void show() const;
friend ostream &operator<<(ostream &os, const vintage &v);
};

#endif

port.cpp

#include"port.h"

port::port(const char *b, const char *s, int bo)

{
int n = strlen(b) + 1;
brand = new char
;
strcpy_s(brand, n, b);
strcpy_s(style, 20, s);
bottle = bo;

}

port::port(const port &p)

{
int n = strlen(p.brand) + 1;
brand = new char
;
strcpy_s(brand, n, p.brand);
strcpy_s(style, 20, p.style);
bottle = p.bottle;

}

port &port::operator=(const port &p)

{
int n = strlen(p.brand) + 1;
brand = new char
;
strcpy_s(brand, n, p.brand);
strcpy_s(style, 20, p.style);
bottle = p.bottle;
return *this;

}

port &port::operator +=(int bo)

{
bottle = bottle + bo;
return *this;

}

port &port::operator -=(int bo)

{
bottle = bottle - bo;
return *this;

}

void port::show() const

{
cout << "Brand :" << brand << endl;
cout << "Style :" <<style << endl;
cout << "Bottle :" << bottle << endl;

}

ostream &operator<<(ostream &os, const port &p)

{
os << p.brand << ", " << p.style << ", " << p.bottle ;
return os;

}

vintage::vintage()

{}

vintage::vintage(const char *n, int y, char *b, char *s, int bo) :port(b,s,bo)

{
int m = strlen(n) + 1;
nickname = new char[m];
strcpy_s(nickname, m, n);
year = y;

}

vintage::vintage(const vintage &v) :port(v)

{
int m = strlen(v.nickname) + 1;
nickname = new char[m];
strcpy_s(nickname, m, v.nickname);
year = v.year;

}

vintage &vintage::operator=(const vintage &v)

{
port::operator=(v);
nickname = v.nickname;
year = v.year;
return *this;

}

void vintage::show() const

{
port::show();
cout << "Nickname :" << nickname << endl;
cout << "Year :" << year << endl;

}

ostream &operator<<(ostream &os, const vintage &v)

{
os << port(v);
os << ", " << v.nickname << ", " << v.year<<endl;
return os;

}

user.cpp

#include"port.h"

int main()

{
port one("Lily", "sweet", 2000);
one+= 6;
one.show();
vintage two("Cucue", 1892, "Lily", "sweet", 2000);
two.show();
vintage three=two;
cout << three;
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++