c++ - 从类模板派生类

标签 c++ templates

我是 C++ 新手。在我的学习阶段,我遇到了以下问题。 我正在尝试从类模板Queue 派生类stack。 编译器在 stack

的构造函数中抛出以下错误
..\src\TrainingDay2.cpp:44:3: error: 'b' was not declared in this scope
   b=a;

请帮忙找出根本原因。

#include <iostream>
using std::cout;
using std::endl;

template<class T> class Queue //Base class
{
private:
    T ArrQueue[20];
protected:
    T* a;
    T* b;
public:

    Queue() { cout<<"QUEUE CONST "<<  endl; }
    void push(T x);
    void pop(void);
};


template <class T>
class stack :public Queue<T> // Derived class
{
public:
    stack():Queue<T>() {
        b=a;
    }
    void pop() {
        b--;
    }
};


int main()
{
    stack<int> S;
    return 0;
}

最佳答案

因为基类是一个模板,其实例化取决于派生类的模板参数,并且您试图命名基类的成员,所以两阶段查找要求您编写 this->b,而不是b

(并且不需要默认构造函数调用。)

stack()
{
    this->b = this->a;
}

void pop()
{
    this->b--;
}

(live demo)

欢迎来到 C++...:P


[C++11: 14.6.2/3]: In the definition of a class or class template, if a base class depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member. [..]

关于c++ - 从类模板派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29030988/

相关文章:

c++ - 中型对象连接和合并的 vector

c++ - 读取由\t 分隔的字符对 C++

c++ - 作为唯一的类成员的引用给出了整数的大小 8

c++ - 一种捆绑检查分配失败并返回错误的整洁方法

c++ - 成员引用基类型 'Node<int> *' 不是结构或 union

C++ 模板挑战

c++ - 调试步骤运行不正常

c++ - boost::bind & boost::function 指向重载或模板化成员函数的指针

php - 当我安装 "Smarty"php 时,您需要锁定文件夹 templates 和 templates_r 以供公共(public)访问吗?

templates - 如何在 Go html/template 中获取 map 元素的结构字段?