【问题标题】:C++ call public parent class method via its derived class objectC++通过其派生类对象调用公共父类方法
【发布时间】:2014-12-30 08:29:05
【问题描述】:

我有一个这样定义的基类:

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;
}

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

namespace yxs
{
    class InputFile : File
    {
    public:
        InputFile(std::string fileName);
        virtual ~InputFile();
    };
}

在另一个不相关的类中,我实例化了子类并尝试调用该方法: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);
    }
}

但是,应用程序无法编译。编译器给出了两条错误信息:

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() 方法时也发生了这些错误。

为什么会发生这个错误?在继承的概念中,是不是可以从子类调用父类的方法?

【问题讨论】:

    标签: c++ inheritance


    【解决方案1】:

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

    class InputFile: public File
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2010-11-01
      • 2017-05-05
      • 1970-01-01
      相关资源
      最近更新 更多