为什么编译器看不到范围内的变量?

Why a compiler do not see a variable in the scope?

OS :Windows 8.1

编译器:GNU C++

我有两个模板 classes:base 和 derived。在基础 class 中,我声明了变量 value。当我尝试从派生的 class 方法应用于 value 时,编译器向我报告错误。 但是如果我不使用模板,我不会收到错误消息。

出现错误信息:

main.cpp: In member function 'void Second<T>::setValue(const T&)':
main.cpp:17:3: error: 'value' was not declared in this scope
   value = val;
   ^

有代码:

#include <iostream>

using namespace std;

template<class T>
class First {
public:
    T value;
    First() {}
};

template<class T>
class Second : public First<T> {
    public:
    Second() {}
    void setValue(const T& val) {
        value = val;
    }
};

int main() {
    Second<int> x;
    x.setValue(10);
    cout << x.value << endl;
    return 0;
}

这段代码有效:

#include <iostream>

using namespace std;

class First {
public:
    int value;
    First() {}
};

class Second : public First {
public:
    Second() {}
    void setValue(const int& val) {
        value = val;
    }
};

int main() {
    Second x;
    x.setValue(10);
    cout << x.value << endl;
    return 0;
}

因为基class是依赖的,也就是说,依赖于你的模板参数T。在那些情况下,非限定名称查找不考虑基class的范围。因此,您必须限定名称,例如,this.

this->value = val;

请注意,MSVC 符合此规则,即使不合格也会解析该名称。