C++ 继承问题,无法调用基类中定义的公共(public)函数

标签 c++

我有一个实现 Logger_IF 的 C++ 类 Logger,它定义了一个纯虚函数:

virtual void log( string message ) = 0;

我想用它自己的接口(interface)将 Logger 扩展到我自己的类。我将我的类命名为 SpecialLogger,它扩展了 SpecialLogger_IF。 SpecialLogger_IF 本身扩展了 Logger。我已经定义:

virtual void log( string message, string extra ) = 0;

在我的 SpecialLogger_IF 类上。据我了解,我应该仍然可以通过 SpecialLogger_IF 和 log("message", "extra") 调用 log("message"),但是我无法让它工作。

#include <iostream>

using namespace std;

class Logger_IF
{
    public:

        virtual void log( string message ) = 0;
        virtual ~Logger_IF() {};
};

class Logger : public Logger_IF
{
    public:

        void log( string message )
        {
            this->out( message );
        }

    protected:

        void out( string message )
        {
            cout << "LOG: " << message << endl;
        }
};

class SpecialLogger_IF : public Logger
{
    public:

        virtual void log( string message, string extra ) = 0;
        virtual ~SpecialLogger_IF() {};
};

class SpecialLogger : public SpecialLogger_IF
{
    public:     
        void log( string message, string extra )
        {
            this->out( message );
            this->extra( extra );
        }

    private:

        void extra( string extra )
        {
            cout << "^ EXTRA: " << extra << endl;
        }
};

int main( int argc, char *argv[] )
{
    Logger_IF* logger = new Logger();
    logger->log( "message" );
    delete logger;

    SpecialLogger_IF* spLogger = new SpecialLogger();
    spLogger->log( "message" );
    spLogger->log( "message", "extra" );
    delete spLogger;
}

我收到以下错误:

testing.cpp:62:27: error: too few arguments to function call, expected 2, have 1
        spLogger->log( "message" );
        ~~~~~~~~~~~~~            ^
testing.cpp:34:3: note: 'log' declared here
                virtual void log( string message, string extra ) = 0;
                ^
1 error generated.

有趣的是,在 void log( string message, string extra ) 中调用 this->out( message ) 确实有效,所以一些继承正在发生。

我正在做的事情是正确且可行的,还是我遗漏了什么。

问候

最佳答案

你的问题是你的双参数函数隐藏了基类中的单参数版本(这是语言设计故意为之,因为它防止的问题多于它造成的问题)。

幸运的是,您可以使用 using 解决这个问题:在您的两个参数日志函数的声明下方,只需编写 using Logger::log;

关于C++ 继承问题,无法调用基类中定义的公共(public)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453609/

相关文章:

C++ 从文件中获取数据以记住上次 session

c++ - 如何在 Qt 正则表达式中模拟负向后断言?

c++ - 为什么在 C++ 中使用 if-else if?

c++ - 我怎样才能摆脱 rand() 的警告? (C++)

c++ - 是在连续空间中分配的嵌套 vector

c++ - 存储霍夫曼树的有效方法

c++ - 作为函数指针的静态方法

c++ - 嵌入式系统单元测试

c++ - 常规转换与 static_cast 与 dynamic_cast

c++ - Boost 和 xml 解析