c++ - C++ 中的继承和模板 - 为什么继承的成员不可见?

标签 c++ inheritance templates

当一个模板从另一个模板公开继承时,基本的公共(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/

相关文章:

c++ - 多个嵌套的相关名称 - 在哪里粘贴 typename 关键字?

templates - Handlebar.js 预编译模板;这是什么意思?

c++ - 在 C++ 中设计一个高性能的数值函数

c++ - 定义类中声明的变量的范围(C++)?

c++ - 在调用函数之前声明函数时出现链接器错误

c++ - 通过初始化列表中的模板类构造函数调用非模板基类的构造函数

javascript - 继承类的原型(prototype)对象如何等于 JavaScript 中原始类的新实例?

c++ - Noughts and Crosss/Tic Tac Toe Player又去了

c++ - 如何在屏幕上多次复制一个 Sprite ,每个 Sprite 都具有相同的代码?

c# - 基类中的派生实例