C++——多重继承

标签 c++

我有一个要求会形成菱形恐惧图案。但是我遇到过堆栈溢出伙伴的评论,如果虚拟基类是一个纯抽象类,那么菱形模式就不是那么重要了。有人可以详细说明为什么会这样吗?

最佳答案

C++ 中的多重继承是一种强大但棘手的工具,如果不小心使用,通常会导致问题。

下面的文章将教您如何使用虚拟继承来解决程序员遇到的一些常见问题。

Solving the Diamond Problem with Virtual Inheritance

尝试按如下方式实现 dimond:文章给出了很好的解释

class storable 
{
        public:
        storable(const char*);
        virtual void read()=0; //this becomes pure virtual making storable an abstract
        virtual void write(); //class
        virtual ~storable();
        private:
        ....
}

class transmitter: public virtual storable 
{
        public:
        void write()
        {
                read();
                ....
        }
} 

class receiver: public virtual storable
{
        public:
        void read();
}

class radio: public transmitter, public receiver
{
        public:
        ...
}

int main()
{
        radio *rad = new radio();
        receiver *r1 = rad;
        transmitter *r2 =rad;

        rad->write();
        r1->write();
        r2->write();
        return 1;
}

关于C++——多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9079583/

相关文章:

c++ - AST : get leaf value when leafs are of different types

c++ - 为什么 Visual Studio 允许我在模板函数 (C++) 中使用私有(private)成员?

c++ - 如何在 C++ 中将 int 连接到 wchar_t*?

c++ - 这个程序会不会导致内存泄漏

c++ - 在 C++ 中删除小数点后的数字(没有 floor() 函数)

c++ - 命名管道上的 WriteFile 有时会返回 ERROR_NO_DATA

c++ - 违反封装?

c++ - 通过引用将对象传递给函数不会更改此对象

c++ - OpenCV - C++ - 如何转换 cv::Scalar 以返回 cv::Scalar 的 C 包装器中的指针?

c++ - CRC16 modbus 计算为长数据包返回错误值