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

相关文章
|
1月前
|
存储 C++
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
24 2
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
|
1月前
|
安全 程序员 编译器
【C++篇】继承之韵:解构编程奥义,领略面向对象的至高法则
【C++篇】继承之韵:解构编程奥义,领略面向对象的至高法则
81 11
|
1月前
|
存储 编译器 C语言
C++类与对象深度解析(一):从抽象到实践的全面入门指南
C++类与对象深度解析(一):从抽象到实践的全面入门指南
48 8
|
1月前
|
C++
C++番外篇——对于继承中子类与父类对象同时定义其析构顺序的探究
C++番外篇——对于继承中子类与父类对象同时定义其析构顺序的探究
53 1
|
1月前
|
C++
C++番外篇——虚拟继承解决数据冗余和二义性的原理
C++番外篇——虚拟继承解决数据冗余和二义性的原理
39 1
|
1月前
|
安全 编译器 程序员
C++的忠实粉丝-继承的热情(1)
C++的忠实粉丝-继承的热情(1)
18 0
|
1月前
|
编译器 C++
C++入门11——详解C++继承(菱形继承与虚拟继承)-2
C++入门11——详解C++继承(菱形继承与虚拟继承)-2
30 0
|
1月前
|
程序员 C++
C++入门11——详解C++继承(菱形继承与虚拟继承)-1
C++入门11——详解C++继承(菱形继承与虚拟继承)-1
32 0
|
2月前
|
C++
C++(二十)继承
本文介绍了C++中的继承特性,包括公有、保护和私有继承,并解释了虚继承的作用。通过示例展示了派生类如何从基类继承属性和方法,并保持自身的独特性。此外,还详细说明了派生类构造函数的语法格式及构造顺序,提供了具体的代码示例帮助理解。
|
9天前
|
存储 编译器 C++
【c++】类和对象(中)(构造函数、析构函数、拷贝构造、赋值重载)
本文深入探讨了C++类的默认成员函数,包括构造函数、析构函数、拷贝构造函数和赋值重载。构造函数用于对象的初始化,析构函数用于对象销毁时的资源清理,拷贝构造函数用于对象的拷贝,赋值重载用于已存在对象的赋值。文章详细介绍了每个函数的特点、使用方法及注意事项,并提供了代码示例。这些默认成员函数确保了资源的正确管理和对象状态的维护。
36 4