c++继承层次结构实践

简介: 这篇文章通过多个示例代码,讲解了C++中继承层次结构的实践应用,包括多态、抽象类引用、基类调用派生类函数,以及基类指针引用派生类对象的情况,并提供了相关的参考链接。

类库开发实践。

一 polymorphic_value.cpp


//https://www.zhihu.com/question/564819820/answer/2747041093

#include <iostream>
#include <vector>
#include <array>
#include <iterator>
#include <memory>
#include <utility>
#include <typeinfo>
#include <cassert>
#include <QCoreApplication>

class Shape
{
   
public:
    std::unique_ptr<Shape> Clone() const
    {
   
        std::unique_ptr<Shape> result = DoClone();
        assert(typeid(*result) == typeid(*this) && "Every derived class must correctly override DoClone.");
        return result;
    }

    virtual void Draw() = 0;

    virtual ~Shape() = default;
protected:
    Shape() = default;

    Shape(const Shape&) = default;
    Shape(Shape &&) = default;
    Shape& operator=(const Shape&) = default;
    Shape& operator=(Shape&&) = default;

private:
    virtual std::unique_ptr<Shape> DoClone() const = 0;
};

class Circle : public Shape
{
   

public:
    void Draw() override
    {
   
        std::cout << "Draw a circle." << std::endl;
    }

private:
    std::unique_ptr<Shape> DoClone() const override
    {
   
        return std::make_unique<Circle>(*this);
    }
};

class Square : public Shape
{
   

public:
    void Draw() override
    {
   
        std::cout << "Draw a Square." << std::endl;
    }

private:
    std::unique_ptr<Shape> DoClone() const override
    {
   
        return std::make_unique<Square>(*this);
    }
};


class Picture
{
   
public:
    explicit Picture(std::unique_ptr<Shape> shape):shape_(std::move(shape)){
   };

    explicit Picture(const Shape& shape):shape_(shape.Clone()){
   }

    Picture(const Picture &rhs) : shape_(rhs.shape_->Clone()){
   }

    Picture& operator=(const Picture& rhs)
    {
   
        if(this!=&rhs)
        {
   
            shape_ = rhs.shape_->Clone();
        }
        return *this;
    }

    Picture(Picture&&) = default;

    Picture& operator=(Picture&&) = default;
    ~Picture() = default;

    void ChangeShape(std::unique_ptr<Shape> shape)
    {
   
        shape_ = std::move(shape);
    }

    void ChangeShape(const Shape& shape)
    {
   
        shape_ = shape.Clone();
    }

    void Draw()
    {
   
        shape_->Draw();
    }

private:
    std::unique_ptr<Shape> shape_;
};

int main(int argc, char *argv[])
{
   
    QCoreApplication a(argc, argv);

    Picture picture1(std::make_unique<Circle>());
    picture1.Draw();
    Picture picture2(std::make_unique<Square>());
    picture2.Draw();

    Picture picture3(picture1);
    picture3.Draw();

    picture3 = picture2;
    picture3.Draw();

    Picture picture4(std::move(picture1));
    picture4.Draw();
    picture4 = std::move(picture2);
    picture4.Draw();

    Picture picture5(std::move(picture1));
    picture5.Draw();
    picture5.ChangeShape(std::make_unique<Square>());
    picture5.Draw();

    Circle circle;
    Square square;

    Picture picture6(circle);
    picture6.Draw();
    picture6.ChangeShape(square);
    picture6.Draw();

    Picture picture7(Circle{
   });
    picture7.Draw();
    picture7.ChangeShape(Square{
   });
    picture7.Draw();

    std::vector<Picture> pictures1;
    pictures1.emplace_back(std::make_unique<Circle>());
    pictures1.emplace_back(std::make_unique<Square>());
    pictures1.emplace_back(Circle{
   });
    pictures1.emplace_back(Square{
   });
    for(auto& picture : pictures1)
    {
   
        picture.Draw();
    }

    std::vector<std::unique_ptr<Shape>> shapes1;
    shapes1.push_back(std::make_unique<Circle>());
    shapes1.push_back(std::make_unique<Square>());
    for(auto& shape : shapes1 )
    {
   
        shape->Draw();
    }

    std::vector<Picture> pictures2{
   picture3,picture4,picture5,picture6,picture7};
    std::vector<Picture> pictures3(pictures1);
    std::vector<Picture> pictures4(std::move(pictures1));

    pictures3 = pictures2;
    pictures4 = std::move(pictures2);

    std::vector<std::unique_ptr<Shape>> shapes2;
    shapes2.push_back(std::make_unique<Circle>());
    shapes2.push_back(std::make_unique<Circle>());
    shapes2.push_back(std::make_unique<Circle>());

    auto init = std::to_array<std::unique_ptr<Shape>>({
   std::make_unique<Circle>(), std::make_unique<Square>()});
    std::vector<std::unique_ptr<Shape>> shape3(std::make_move_iterator(init.begin()), std::make_move_iterator(init.end()));

    std::vector<std::unique_ptr<Shape>> shapes5(std::move(shapes1));
    shapes5 = std::move(shapes2);

    return a.exec();
}

二 AbstractClassReference.cpp

//https://blog.csdn.net/daydr/article/details/121789356
//https://my.oschina.net/hanshubo/blog/1600658

#include<iostream>
using namespace std;
class Number
{
   
    public:
    Number(int i)
    {
   
        val=i;
    }
    virtual void show()const=0;//纯虚函数
    protected:
    int val;
};

class Hex:public Number
{
   
    public:
    Hex(int i):Number(i){
    }
    void show()const//别忘记后面的const
    {
   cout<<"Hex="<<val<<endl;}
};

class Dex:public Number
{
   
    public:
    Dex(int i):Number(i) {
    }
    void show()const
    {
   cout<<"Dex="<<val<<endl;}
};

class Oct:public Number
{
   
    public:
    Oct(int i):Number(i) {
    }
    void show()const
    {
   
        cout<<"Oct="<<val<<endl;
    }
};

void fun(Number &n)//普通函数定义引用抽象类的引用参数
{
   
    n.show();
}

void FUNShared(shared_ptr<Number> n)
{
   
    n->show();
}

int main()
{
   
#if 0
    Dex n1(50);
    fun(n1);//Dex::show();
    Hex n2(70);
    fun(n2);//Hex::show()
    Oct n3(29);
    fun(n3);//Oct::show()
#else

//    shared_ptr<Dex> n1(new Dex(50));
//    auto n1 = std::make_shared<Dex>(50);

    shared_ptr<Dex> n1 = std::make_shared<Dex>(50);
    FUNShared((std::shared_ptr<Number>)(n1));//Dex::show();
    FUNShared(static_pointer_cast<Number> (n1));//Dex::show();

    shared_ptr<Hex> n2 = std::make_shared<Hex>(70);
    FUNShared(static_pointer_cast<Number> (n2));//Hex::show()

    shared_ptr<Oct> n3 = std::make_shared<Oct>(29);
    FUNShared(static_pointer_cast<Number> (n3));//Hex::show()

    auto p2 = std::make_shared<string>("s");

#endif

}

三 baseCallDeriveFun.cpp

//https://blog.csdn.net/daydr/article/details/121863051
//https://blog.csdn.net/weixin_46222091/article/details/104832221

#include<iostream>
#include<cstring>
#include<memory.h>>
using namespace std;
class A_class
{
   
    char name[20];
    public:
    void put_name(char * s)
    {
   
        strcpy_s(name,s);
    }
    void show_name()const
    {
   cout<<name<<"\n";}
};
class B_class:public A_class
{
   
    char phone_num[20];
    public:
    void put_phone(char * num)
    {
   strcpy_s(phone_num,num);}
    void show_phone()const
    {
   cout<<phone_num<<"\n";}
};

int main()
{
   
#if 0
    A_class * A_p;
    A_class A_obj;
    B_class B_obj;
    A_p=&A_obj;
    A_p->put_name((char*)"Wang Liao hua");
    A_p->show_name();
    A_p=&B_obj;//基类指针指向派生类指针
    A_p->put_name((char*)"chen ming");//调用基类成员函数
    A_p->show_name();
    B_obj.put_phone((char*)"3333_12345678");//调用派生类成员函数
    ((B_class*)A_p)->show_phone();//对基类指针进行强制化转化

    //wrong
//    A_p=&B_obj;
//    A_p->put_phone((char*)"3333_12345678");
//    A_p->show_phone();

#else

//    cout << "使用智能指针" << endl;
    shared_ptr<A_class> *A_p;
//    shared_ptr<A_class*> A_p;
    shared_ptr<A_class> A_obj = make_shared<A_class>();
    shared_ptr<B_class> B_obj = make_shared<B_class>();

    A_p=&A_obj;
    A_p->get()->put_name((char*)"Wang Liao hua");
    A_p->get()->show_name();

//基类指针指向派生类指针 TODO
//    A_p=&B_obj;
//    A_p = std::dynamic_pointer_cast<B_class>(B_obj);
//    A_p = static_pointer_cast<B_class>(B_obj);
//    static_pointer_cast<B_class>(A_p)->get()->put_name((char*)"chen ming");//调用基类成员函数
//    A_p->get()->show_name();
//    static_pointer_cast<B_class>(A_p)->get()->put_name((char*)"chen ming");//调用基类成员函数
//    B_obj->get()->put_phone((char*)"3333_12345678");//调用派生类成员函数
//    ((B_class*)A_p)->show_phone();//对基类指针进行强制化转化
//    static_pointer_cast<B_class>(A_p)->show_phone();

#endif


}

四 ReferencesBaseObjectsWithDerivedClassPointers.cpp

//https://blog.csdn.net/daydr/article/details/121863051
//https://blog.csdn.net/xiaobai_xuec/article/details/124830524

#include<iostream>
#include<cstring>
using namespace std;

class Date
{
   

public:
    Date(int y,int m,int d)
    {
   
        SetDate(y,m,d);
    }

    void SetDate(int y,int m,int d)
    {
   
        year=y;
        month=m;
        day=d;
    }

    void print()
    {
   
        cout<<year<<'\''<<month<<"\'"<<day<<";";
    }

protected:
    int year,month,day;
};

class Datetime:public Date
{
   

public:
    Datetime(int y,int m,int d,int h,int mi,int s):Date(y,m,d)
    {
   
        settime(h,mi,s);
    }

    void settime(int h,int mi,int s)
    {
   
        hours=h;
        minutes=mi;
        seconds=s;
    }

    void print()const
    {
   
        cout<<hours<<":"<<minutes<<":"<<seconds<<":"<<'\n';
    }

private:
    int hours,minutes,seconds;
};

int main()
{
   

#if 0

//    Datetime dt(2021,12,22,12,30,0);
//    Datetime*pdt=&dt;
//    ((Date)dt).print();//对象类型的转化,调用基类函数
//    dt.print();
//    ((Date*)pdt)->print();//对象指针类型的转化,调用基类函数
//    pdt->print();

#else

    std::shared_ptr<Datetime> dt(new Datetime(2021,12,22,12,30,0));
    std::shared_ptr<Datetime> *pdt = &dt;
    static_pointer_cast<Date>(dt)->print();
    dt->print();//2021'12'22;12:30:0:

//    ((Date*)pdt)->print();
//    pdt->get()->print();//-1648667856'428'-1648667760;12:30:0:

    ((std::shared_ptr<Date> *)pdt)->get()->print();
    pdt->get()->print();//2021'12'22;12:30:0:

#endif

//    shared_ptr<int> p(new int(1));
//    shared_ptr<int> p1 = p;    // p和p1指向同一块内存
//    shared_ptr<int> p2;
//    // 使用reset初始化share_ptr
//    p2.reset(new int(1));    // p2和p3指向同一块内存
//    shared_ptr<int> p3(p2);
//    cout << (int*)&(*p) << endl;
//    cout << (int*)&(*p1) << endl;
//    cout << (int*)&(*p2) << endl;
//    cout << (int*)&(*p3) << endl;

//    shared_ptr<void> point(new int(1)); //共享指针内部保存void型指针
//    shared_ptr<int> point1(static_cast<int *>(point.get())); //compile error,undefined pointer
//    static_pointer_cast<int *>(point);    // OK

//    static_pointer_cast
//    dynamic_pointer_cast
//    const_pointer_cast
}

五 参考链接

https://www.zhihu.com/question/564819820/answer/2747041093
https://blog.csdn.net/daydr/article/details/121789356
https://my.oschina.net/hanshubo/blog/1600658
https://blog.csdn.net/daydr/article/details/121863051
https://blog.csdn.net/weixin_46222091/article/details/104832221
https://blog.csdn.net/daydr/article/details/121863051
https://blog.csdn.net/xiaobai_xuec/article/details/124830524

相关文章
|
11天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
8天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2522 17
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
8天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1525 15
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
|
4天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
10天前
|
编解码 JSON 自然语言处理
通义千问重磅开源Qwen2.5,性能超越Llama
击败Meta,阿里Qwen2.5再登全球开源大模型王座
589 14
|
1月前
|
运维 Cloud Native Devops
一线实战:运维人少,我们从 0 到 1 实践 DevOps 和云原生
上海经证科技有限公司为有效推进软件项目管理和开发工作,选择了阿里云云效作为 DevOps 解决方案。通过云效,实现了从 0 开始,到现在近百个微服务、数百条流水线与应用交付的全面覆盖,有效支撑了敏捷开发流程。
19283 30
|
10天前
|
人工智能 自动驾驶 机器人
吴泳铭:AI最大的想象力不在手机屏幕,而是改变物理世界
过去22个月,AI发展速度超过任何历史时期,但我们依然还处于AGI变革的早期。生成式AI最大的想象力,绝不是在手机屏幕上做一两个新的超级app,而是接管数字世界,改变物理世界。
491 49
吴泳铭:AI最大的想象力不在手机屏幕,而是改变物理世界
|
1月前
|
人工智能 自然语言处理 搜索推荐
阿里云Elasticsearch AI搜索实践
本文介绍了阿里云 Elasticsearch 在AI 搜索方面的技术实践与探索。
18842 20
|
1月前
|
Rust Apache 对象存储
Apache Paimon V0.9最新进展
Apache Paimon V0.9 版本即将发布,此版本带来了多项新特性并解决了关键挑战。Paimon自2022年从Flink社区诞生以来迅速成长,已成为Apache顶级项目,并广泛应用于阿里集团内外的多家企业。
17530 13
Apache Paimon V0.9最新进展
|
2天前
|
云安全 存储 运维
叮咚!您有一份六大必做安全操作清单,请查收
云安全态势管理(CSPM)开启免费试用
367 4
叮咚!您有一份六大必做安全操作清单,请查收