栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

学完C再学C++(6)继承类

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

学完C再学C++(6)继承类


#include 
#include 
#include
#include "study.h"//里面写的#define DAY1....


#ifdef DAY7
//练习课后题4.  课后题3给人感觉完全没卵用,强行为了抽象而抽象.
#ifndef Hfile
//头文件部分
using namespace std;
//基类
class port
{
private:
    char* brand;    //应该是型号
    char style[20];//红酒品类吧
    int bottles;    //酒的数量

public:
    port(const char* br = "none", const char* st = "none", int bo = 0);
    port(const port& p);//防止构造时生成默认的,默认的会直接复制对象,里面指针还是没变
    virtual    ~port() { delete[] brand; }
    port& operator=(const port& p);
    port& operator+=(int b);
    port& operator-=(int b);
    virtual void show()const;
    int bottle_count()const { return bottles; }
    friend ostream& operator<<(ostream& os, const port& p);

};
//老程序员留的烂摊子,派生类
//问题b:为什么有些方法重新定义了,有些没有?
//答:因为show多了nickname和year,等号也需要给新的这些成员赋值
//问题c:为什么这个没有将operator=和operator<<声明成虚的?
//答:operator<<声明成了友元函数,没理由变成虚的,等号是因为若是等号也虚了,那么指针就无法相互转换了 
// 比如vp *a= b(p) 就会变成 vp::operator=(b);那最后就变成直接重新分配了一个空间给*a,虚函数作用就体现不出来了.
//声明成虚的那两个,析构函数必须保证能释放完全,show则是也要想显示完全
class vin_port :public port
{
private:
    char* nickname;
    int year;
public:
    //vin_port();
    vin_port(const char *br="none", int bo=0, const char* nn="none", int y=0);
    vin_port(const vin_port& p);
    ~vin_port() { delete[] nickname; }
    vin_port& operator=(const vin_port& vp);
    void show()const;
    friend ostream& operator<<(ostream& os, const vin_port& vp);

};


#endif

//基类部分
port::port(const char* br , const char* st , int bo)
{
    int len = strlen(br)+1 ;
    brand = new char[len];
    memcpy(brand,br,len);
    len= strlen(st);
    memcpy(style, st,len);
    bottles = bo;
}
port::port(const port& p)
{
    int len = strlen(p.brand)+1;
    brand = new char[len];
    memcpy(brand, p.brand, len);
    len = strlen(p.style);
    memcpy(style, p.style, len);
    bottles = p.bottles;
}
//为了防止赋值时把指针也复制过去
port& port::operator=(const port& p)
{
    if (this == &p)return *this;
    free(brand);//先释放原来的
    int len = strlen(p.brand)+1;
    brand = new char[len];
    memcpy(brand, p.brand, len);
    len = strlen(p.style);
    memcpy(style, p.style, len);
    bottles = p.bottles;
    return *this;
}
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 << "Bottles:" << bottles << endl;
}
//友元函数,返回os是为了os 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949824.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号