从派生类

时间:2017-02-02 17:02:41

标签: c++ inheritance abstract-class

我仍然试图抓住抽象基类的概念,以及从Derived类可以做什么和不可以做什么。

我有以下代码:

class NpBaseTest {
    ...
    friend std::ostream& operator<<(std::ostream &os, const NpBaseTest& p_npBaseTest);
    /* Implemented in the .cpp file as -
    std::ostream& operator<<(std::ostream &os, const NpBaseTest& p_npBaseTest)
    {
        p_npBaseTest.show(os);
        return os;
    }
    */
    virtual uint16_t process(int) const = 0;

    virtual void show(std::ostream& os) const
    {
        os
            << "Test ID [" << get_test_id() << "] "
            << "Module Type [" << get_module_type() << "]" << std::endl;
    }
};

class CavTest : public NpBaseTest
{
    ...
    friend std::ostream& operator<<(std::ostream &os, const CavTest& p_cavtest);
    /* Implemented in the .cpp file as
    std::ostream& operator<<(std::ostream &os, const CavTest& p_cavtest) 
    {
        p_cavtest.show(os);
        return os;
    }
    */

    uint16_t process(int p_val) const
    {
        //...implemented here
    }

    void show(std::ostream& os) const
    {
        NpBaseTest::show(os);
        os
            << "CavTest Type" << std::endl;
    }
};

我希望在派生类show函数中做什么,从基类调用show函数但是我得到以下错误。 我的理解是因为NpBaseTest是一个ABC,它在实例化Derived类对象时不会实例化一个对象。 那么我有哪些选择来实现所需的功能呢?

错误讯息:

  

components / cavium / CavTest.cpp:在函数'void show(std :: ostream&amp;)'中:   components / cavium / CavTest.cpp:20:错误:无法调用成员函数   'virtual void NpBaseTest :: show(std :: ostream&amp;)const'没有对象

更新: 初步问题解决了。 寻求更多建议 有没有更好的方法来调用基类函数而不必使用this-&gt; :: show(os)指定基类名?

解决方案: 我将基类show()例程更改为非虚拟私有成员函数,该函数又调用由每个派生类实现的纯虚拟show_all(ostream &os)函数。这样我就不必为每个派生类重新定义operator<<,并且可以避免使用<BaseClassName>::show()

基类中的示例 -

void NpBaseTest::show(std::ostream& os) const
{
    //Do base functionality here
    os
        << "Test ID [" << get_test_id() << "] "
        << "Module Type [" << get_module_type() << "]" << std::endl;

    // Call derived class routine here
    show_all(os); //This is declared as virtual void show_all(ostream& os) const = 0;
}

在派生类

void CavTest::show_all(std::ostream& os) const
{
    os
        << "CavTest Type" << std::endl;
}

1 个答案:

答案 0 :(得分:0)

如图所示,您当前的问题与抽象(a.k.a。纯虚拟)方法无关,因为没有涉及这些方法。

问题1:成员函数声明语法

基类show()有一个额外的NpBaseTest::限定符,不应该存在。在类声明之外定义成员函数时,只需要额外的限定符。通常情况如下:

// Foo.hpp
class Foo
{
    void bar();
}

// Foo.cpp
#include "Foo.hpp"
void Foo::bar()
{
    // ...
}

这是您显示错误消息的最可能原因。

问题2:可见性

基类show()是私有的,因为在class中,默认的可见性为private。你不能从派生类调用私有基类方法,即你对NpBaseTest::show()的调用 - 虽然语法正确 - 不会编译。

问题3:类声明语法

两个班级宣言都错过了;在他们的结束后。

为了得到这个来编译的简单骨骼是:

class NpBaseTest
{
protected: // or: public:
    virtual void show(std::ostream& os) const { /*...*/ }
};

class CavTest : public NpBaseTest
{
    // private by default
    // Works because you can override with a lower visibility,
    // but not with a higher one.

    void show(std::ostream& os) const override
    {
        NpBaseTest::show(os);
        // ...
    }
};

override是可选的,但强烈建议使用支持C ++ 11的(即非古老的)编译器。

相关问题