小编Yur*_*ash的帖子

通过此指针调用受保护的基类方法,该指针在派生类(C++)中转换为基类

首先,我了解C++标准(ISO/IEC 14882:2003):第11.5节,第1段,这不是那种情况(但是compliler显然不这么认为).

我尝试通过这个指针在派生类方法中调用受保护的基类方法,静态转换为基类指针并在MSVC2008中出现错误C2248:'A :: f':无法访问在类'A'中声明的受保护成员.

必须在"奇怪的重复模板模式"的上下文中执行此操作,但我可以在更简单的代码中重现此错误,如下所示:

class B
{
protected:
    void f(){}
};

class D : public B
{
public:
    void g()
    {
        f(); // ok
        this->f(); // ok
        static_cast<B*>(this)->f(); // C2248 in MSVC2008
        dynamic_cast<B*>(this)->f(); // C2248
        ((B*)this)->f(); // C2248
    }
};
D d; d.g();
Run Code Online (Sandbox Code Playgroud)

似乎编译器认为将此指针作为指向其他实例的指针,是吗?

在这种情况下编译器是错误的,你怎么看?


好的,我的真实代码更像是:

template<class T>
class B
{
public:
    void g()
    {
        f(); // error C3861: 'f': identifier not found
        this->f(); // error C3861: 'f': …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance compiler-errors protected

6
推荐指数
1
解决办法
1852
查看次数

标签 统计

c++ ×1

compiler-errors ×1

inheritance ×1

protected ×1