当一个模板从另一个模板公开继承时,基本的公共(public)方法不应该是可访问的吗?
template <int a>
class Test {
public:
Test() {}
int MyMethod1() { return a; }
};
template <int b>
class Another : public Test<b>
{
public:
Another() {}
void MyMethod2() {
MyMethod1();
}
};
int main()
{
Another<5> a;
a.MyMethod1();
a.MyMethod2();
}
好吧,GCC 在这方面废话了……我一定遗漏了一些完全明显的东西(大脑融化)。帮忙?
最佳答案
这是有关从属名称的规则的一部分。 Method1
不是 Method2
范围内的从属名称。所以编译器不会在依赖的基类中查找它。
有两种方法可以解决这个问题:使用 this
或指定基本类型。更多详情 very recent post或在 C++ FAQ .另请注意,您错过了 public 关键字和分号。这是您的代码的固定版本。
template <int a>
class Test {
public:
Test() {}
int MyMethod1() { return a; }
};
template <int b>
class Another : public Test<b>
{
public:
Another() {}
void MyMethod2() {
Test<b>::MyMethod1();
}
};
int main()
{
Another<5> a;
a.MyMethod1();
a.MyMethod2();
}
关于c++ - C++ 中的继承和模板 - 为什么继承的成员不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567730/