类继承保护的访问

时间:2018-12-15 07:30:42

标签: c++ inheritance template-meta-programming protected

我正在玩我创建的测试课程。代码链接在下面。

template<bool...rest_of_string>
class bitstring
{
public:
    void print_this_handler()
    {
        cout << " END";
    }
};

template<bool A, bool... rest_of_string>
class bitstring<A, rest_of_string...> : public bitstring<rest_of_string...>
{
public:
    static const bool value = A;

    bitstring(){}

    void print_this()
    {
        cout << "\nPrinting Bitstring with " << sizeof...(rest_of_string) << " bits: ";
        print_this_handler();
    }
protected:

    void print_this_handler()
    {
        cout << A;
        static_cast<bitstring<rest_of_string...> >(*this).print_this_handler();
    }
};

int main()
{
    bitstring<0,1,0,1,0,1,1,0> str;
    str.print_this();
}

当我从print_this()内部调用print_this_handler()时遇到错误。它说print_this_handler()在类bitstring中受保护。但是,每个类都是从位串派生的,那么为什么我不能访问下一个最高的类呢?当我更改为“受保护的公众”时,一切正常,但是我很好奇为什么这样做不起作用。谢谢。

精确错误消息复制到下面:

C:\Users\main.cpp|195|error: 'void bitstring<A, rest_of_string ...>::print_this_handler() [with bool A = true; bool ...rest_of_string = {false, true, false, true, true, false}]' is protected within this context|

1 个答案:

答案 0 :(得分:2)

您正试图调用基类print_this_handler,因此您只需要指定基类并直接调用它,尝试通过强制转换指针来实现就可以解决此问题。如果您这样想,则将this指针转换为基类时,就好像您已经创建了基类的实例,然后尝试调用受保护的成员函数一样。您不能这样做,但是如果仅添加消除歧义的功能来指定基类函数,就没有问题,您可以直接调用它。您可以查看此SO问题/答案,以得到更多的澄清和解释:https://stackoverflow.com/a/357380/416574

更改此行:

static_cast<bitstring<rest_of_string...> >(*this).print_this_handler();

对此:

bitstring<rest_of_string...>::print_this_handler();
相关问题