我遇到了与此前的问题相同,链接如下:
Use of undeclared identifier in C++ with templates and inheritance
总结一下,我们试图从子类中访问模板类的保护属性。应该使用
编辑: 下面是我用于在Visual Studio 2012中测试的代码。
使用g++编译会失败,但使用Visual Studio 2012可以成功编译。
this->attribute
而不是仅使用attribute
。然而,我想知道为什么在Visual Studio 2012中不需要添加this->,程序可以正确编译和执行。我也想知道是否有办法在OS X上的gcc或其他编译器中实现这个功能。编辑: 下面是我用于在Visual Studio 2012中测试的代码。
//file a.h
template<class T>
class a
{
public:
a(){value = 2;};
protected:
T value;
};
template<class T>
class b: public a<T>
{
public:
T getValue(){return value;};
};
//file main.cpp
#include <iostream>
#include "a.h"
using namespace std;
int main()
{
b<int> myTest;
cout<<myTest.getValue();
system("pause");
return 0;
}
使用g++编译会失败,但使用Visual Studio 2012可以成功编译。