C++通过其派生类对象调用公共父类方法

yun*_*awa 3 c++ inheritance

我有一个我定义的基类,如下所示:

namespace yxs
{
    class File
    {
    public:
        File(std::string fileName);
        virtual ~File();
        bool isExists();
        size_t size();

    protected:
        std::string fileName;
        std::ifstream* inputStream;
        std::ofstream* outputStream;
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个继承上述基类的子类:

namespace yxs
{
    class InputFile : File
    {
    public:
        InputFile(std::string fileName);
        virtual ~InputFile();
    };
}
Run Code Online (Sandbox Code Playgroud)

在另一个不相关的类中,我实例化了子类并尝试调用该方法: isExists()

void yxs::Engine::checkFile()
{
    bool isOK = this->inputFile->isExists(); // Error on compile in this line

    if(!isOK)
    {
        printf("ERROR! File canot be opened! Please check whether the file exists or not.\n");

        exit(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,该应用程序将无法编译.编译器给出了两条错误消息:

Engine.cpp:66:34: 'isExists' is a private member of 'yxs::File'

和:

Engine.cpp:66:17: Cannot cast 'yxs::InputFile' to its private base class 'yxs::File'

当我尝试调用size()方法时,也会发生这些错误.

为什么会发生此错误?在继承概念中,允许从它的子进程调用父类方法不是吗?

Bra*_*orm 6

您需要将其从私有继承更改为公共继承:

class InputFile: public File
Run Code Online (Sandbox Code Playgroud)

如果没有public关键字,File的所有成员都将成为InputFile的私有成员.