【问题标题】:class inheritance protected access类继承保护访问
【发布时间】:2019-05-16 08:35:54
【问题描述】:

我正在玩我创建的测试类。代码链接如下。

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() 在类位串中受到保护。但是,每个类都派生自位串,那么为什么我不能访问下一个最高的类呢?当我将保护更改为公开时​​,一切正常,但我只是好奇为什么这不起作用。谢谢。

下面复制的确切错误消息:

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|

【问题讨论】:

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


    【解决方案1】:

    您正在尝试调用基类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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 2023-03-23
      • 2017-09-26
      • 2016-02-29
      相关资源
      最近更新 更多