我是 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/