TiP*_*iPo 3 c++ scope gnu compiler-errors
操作系统:Windows 8.1
编译器:GNU C++
我有两个模板类:base和derived.在基类中我声明了变量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;
^
Run Code Online (Sandbox Code Playgroud)
有代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码是有用的:
#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;
}
Run Code Online (Sandbox Code Playgroud)
因为基类是依赖的,即依赖于模板参数T.在这些情况下,非限定名称查找不考虑基类的范围.因此,您必须使用例如此限定名称.
this->value = val;
Run Code Online (Sandbox Code Playgroud)
请注意,MSVC 不符合此规则,即使名称不合格,也会解析名称.