【问题标题】:C++ "was not declared in this scope" when overriding a pure virtual method in a derived class在派生类中覆盖纯虚方法时,C++“未在此范围内声明”
【发布时间】:2012-07-01 10:57:15
【问题描述】:

这是我需要做的:

#include <iostream>                                                                                                                                                                                              

using namespace std;

class A
{
    public :
    virtual void fa() = 0;
};

template <typename type>
class B : public A
{
    protected :
    int v_b;
};

template <typename type>
class C : public B<type>
{
    public :
    void fa()
    {
        // whatever action that try to access v_b
        cout << "v_b = " << v_b << endl;
    }
};

int main()
{
    C<int> toto;
    toto.fa();
    return 0;
}

这里是 g++ 输出:

test.cpp: In member function ‘void C<type>::fa()’:
test.cpp:25:29: error: ‘v_b’ was not declared in this scope

据我了解,v_b 是 B 的受保护成员,因此可以在 C 中访问。A 和 B 都是抽象类,我需要在 C 类中重写 A 的 f_a() 方法才能实例化它。因为编译器告诉我这个

test.cpp: In member function ‘void C<type>::fa()’:

‘void A::fa()’:

我不明白为什么 v_b 变量不在范围内。这是我使用模板方式的问题吗?

谁能帮我解决这个问题?

谢谢

编辑:

我尝试按照here 的建议使用 this->v_b 或 B::v_b 并且它工作正常!谢谢你的帮助

【问题讨论】:

标签: c++ templates inheritance scope overriding


【解决方案1】:

在表达式中:

    cout << "v_b = " << v_b << endl;

v_b 是一个非依赖表达式(即它不像看起来依赖于模板参数。对于非依赖表达式,第一阶段查找必须解析符号,并且它将通过仅查看非依赖上下文来做到这一点。这不包括模板化基础(因为它依赖于类型参数)。简单的解决方法是使用 this 限定调用:

    cout << "v_b = " << this->v_b << endl;

现在它是一个依赖表达式(this 这显然取决于实例化类型),并且查找被延迟到第二阶段,其中类型被替换并且可以检查碱基。

【讨论】:

  • 感谢您的快速回答,甚至比我的编辑还要快!我试图朝那个方向看,但我仍然有一些我不明白的问题。请你看看发生了什么?非常感谢您的帮助
  • 不,你是对的!在尝试测试不同的解决方案时,尽管看起来很绝望,但我在编辑时留下了一个“模板 class C:public B {”!感谢您指出这一点!我现在可以睡觉了;)
猜你喜欢
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2021-07-17
  • 2015-08-21
  • 2015-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多