【发布时间】: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<T>::value = val;时,它也可以工作。 (coliru.stacked-crooked.com/a/3f6103bc3ae99c8f) -
@SimonKraemer:MSVC 在这种情况下不兼容。
-
@ArmenTsirunyan 我不再对此感到惊讶。
标签: c++ scope compiler-errors gnu