gpt4 book ai didi

c++ - 类继承保护访问

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:17 24 4
gpt4 key购买 nike

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

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

下面复制了准确​​的错误消息:

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|

最佳答案

您正在尝试调用基类 print_this_handler 因此您只需要指定基类并直接调用它,尝试通过强制转换的指针执行此操作会给您带来这个问题。如果你这样想,当你将 this 指针强制转换为基类时,就好像你创建了一个基类的实例,然后试图调用一个 protected 成员函数。你不能那样做,但是如果你只是添加消歧来指定基类函数就没有问题,你可以直接调用它。您可以查看此 SO 问题/答案以获得更多说明和解释:https://stackoverflow.com/a/357380/416574

改变这一行:

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

对此:

bitstring<rest_of_string...>::print_this_handler();

关于c++ - 类继承保护访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com