<分区>
考虑以下代码:
template<class T> class Foo
{
public:
Foo() { a = 1; }
protected:
int a;
};
template<class T> class Bar : public Foo<T>
{
public:
Bar() { b = 4; };
int Perna(int u);
protected:
int b;
};
template<class T> int Bar<T>::Perna(int u)
{
int c = Foo<T>::a * 4; // This works
return (a + b) * u; // This doesn't
}
g++ 3.4.6、4.3.2 和 4.1.2 给出错误
test.cpp: In member function `int Bar<T>::Perna(int)':
test.cpp:25: error: `a' was not declared in this scope
g++ 2.96 和 MSVC 6、7、7.1、8 和 9 接受它,(至少)旧的 Intel 和 SGI c++ 编译器也接受它。
新的 Gnu C++ 编译器是否符合标准?如果他们这样做,继承类无法看到 protected 继承成员变量背后的基本原理是什么?
还有,如果有
int A() { return a; }
在 Foo 中,我得到错误
test.cpp:25: error: there are no arguments to A that depend on a template parameter, so a declaration of A must be available
test.cpp:25: error: (if you use -fpermissiveâ, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
当我尝试在 Bar 的成员函数中使用它时。 我也觉得奇怪:Bar 继承了 Foo,所以我认为很明显 Bar 范围内的 A() 是 Foo::A()。