从类模板派生一个类 [英] Deriving a class from a class template

查看:43
本文介绍了从类模板派生一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to C++. During my learning phase I encountered with below issue. I am trying to derive a class stack from a class template Queue. Compiler throws below error in constructor of 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;
}

推荐答案

原因是在模板内部应用了两阶段名称查找规则:

The reason is that inside a template, two-phase name lookup rules apply:

  • 在定义(=已分析)模板时,查找(=已解析)不依赖模板参数的名称.

  • Names which do not depend on template parameters are looked up (=resolved) when the template is defined (=parsed).

在实例化模板时(当您提供模板参数时)会查找确实依赖于模板参数的名称.

Names which do depend on template parameters are looked up when the template is instantiated (when you provide the template arguments).

取决于模板参数的基类仅在实例化名称查找期间进行搜索.

Base classes which depend on template parameters are only searched during name lookup at instantiation time.

进行此两阶段查找的原因是,在知道模板参数之前,编译器无法知道基类(或其他从属构造)的定义.请记住,存在模板专用化.

The reason for this two-phase lookup is that until the template arguments are known, the compiler cannot know what the definition of the base class (or other dependent construct) will be. Remember that template specialisation exists.

您需要以某种方式告诉编译器名称 b 是从属的.基本上,您可以通过三种方式做到这一点:

You need to somehow tell the compiler that the name b is dependent. You basically have three ways to do that:

  1. 使用 this-> 前缀名称;由于您位于类模板中,因此所有成员都隐式依赖模板参数:

  1. Prefix the name with this->; since you're in a class template, all your members depend on template parameters implicitly:

this->b = a;

  • 使用完全限定的名称.这将使对模板参数的依赖性明确:

  • Use full qualification for the name. This will make the dependency on template parameters explicit:

    Queue<T>::b = a;
    

  • 在类中放置一个 using 声明,以通知编译器该名称来自于依赖的基类:

  • Put a using declaration into your class to inform the compiler that the name comes from a dependent base class:

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

  • 这篇关于从类模板派生一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆