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

标签 c++ scope compiler-errors gnu

<分区>

操作系统:Windows 8.1

编译器:GNU C++

我有两个模板类:基类和派生类。在基类中,我声明了变量 value。当我尝试从派生类的方法应用于 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;
}

最佳答案

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

this->value = val;

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

关于c++ - 为什么编译器看不到范围内的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415662/

相关文章:

标准保证C++新建/删除复杂度

来自 header 的静态函数的c++怪异行为

ios - 全局变量在不存在时被识别为 null - Objective C

c++ - 编译可在Mac上运行,但不能在群集上运行(Linux)

Java Magic Square - 求和列和求和行错误

c++ - 如何一直显示当前函数的注释?

c++ - 将 const 与 typedef 类型一起使用

c - 错误 : expected declaration specifiers or '...' before XXX (all kinds of parameters)

c++ - 如何知道某个指针是否已在其他地方释放

python - 为什么静态绑定(bind)对类和函数的作用不同?