从子类到具有相同基数的抽象子类的隐式转换

Implicit conversion from child class to abstract child class with the same base

本文关键字:子类 抽象 转换      更新时间:2023-10-16

是否可以将派生类隐式转换为具有公共基数的抽象派生类,而无需先强制转换为基数?

例:

class IOBase
{
public:
    virtual std::vector<unsigned char> read(int size) = 0;
    virtual void write(const std::vector<unsigned char> & data) = 0;
};
// Derived abstract class
class Input : public IOBase
{
private:
    using IOBase::write;
};
// File IO derived class
class FileIO : public IOBase
{...}
class FileInput : public FileIO
{
private:
    using FileIO::write;
};

void ReadFromInput(Input& input) {...}
void main()
{
    FileInput fi;
    ReadFromInput(fi); <-- compiler error, 
                           should be first casted to base class IOBase and
                           then to abstract class Input
    FileIO f;
    ReadFromInput(f); <-- compiler error
}

请注意,readwrite 方法不能是常量。

你的FileIO不是从Input派生的,所以不仅不能省略强制转换,而且实际上甚至不允许强制转换,因为在你的完整对象fi的任何地方都没有Input子对象。

似乎您可能需要虚拟基类:

class Input : public virtual IOBase { /* ... */ };
class FileIO : public virtual IOBase { /* ... */ };
class FileInput : public Input, public FileIO { /* ... */ };

然后,您的通话中就不需要演员表。