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