【问题标题】:Why a compiler do not see a variable in the scope? [duplicate]为什么编译器在范围内看不到变量? [复制]
【发布时间】:2016-05-26 17:38:04
【问题描述】:

操作系统: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;
}

【问题讨论】:

  • 不合格的查找不查找依赖的基类。那里肯定有无数个重复...
  • 适用于 VS2015。当您将value = val; 更改为First&lt;T&gt;::value = val; 时,它也可以工作。 (coliru.stacked-crooked.com/a/3f6103bc3ae99c8f)
  • @SimonKraemer:MSVC 在这种情况下不兼容。
  • @ArmenTsirunyan 我不再对此感到惊讶。

标签: c++ scope compiler-errors gnu


【解决方案1】:

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

this->value = val;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多