C++模板中子类继承父类出现 找不到标识符 的错误
C++模板中子类继承父类出现 找不到标识符 的错误提要在使用子类模板继承父类模板的时候,子类使用父类的protected成员变量时出现 找不到标识符 的错误代码如下父类 vector#include "pch.h"#include <iostream>using namespace std;template <class T>class vector {protected:
·
C++模板中子类继承父类出现 找不到标识符 的错误
提要
在使用子类模板继承父类模板的时候,子类使用父类的protected成员变量时出现 找不到标识符
的错误
代码如下
父类 vector
#include "pch.h"
#include <iostream>
using namespace std;
template <class T>
class vector {
protected:
//当前容器内元素的个数
int vectorSize;
T *vectorNode;
//当前容器的大小
int initSize = 10;
public :
//含参构造函数
vector(int capicity);
//构造函数
vector();
//析构函数
~vector();
//插入元素
bool push(T data);
//弹出元素
T pop();
//返回容器的大小
int size();
//返回指定位置的元素
T at(int location);
//清空容器中所有的元素
void clear();
};
子类 stack
#include "pch.h"
#include <iostream>
#include "vector.cpp"
using namespace std;
template <class T>
class stack :public vector<T> {
public:
//返回栈顶元素
T top();
private:
//修改父类at()方法的访问权限
T at(int location);
};
template <class T>
T stack<T>::top() {
if (vectorSize == 0) {
throw range_error("the size of vector is zero");
}
else {
return *(this->vectorNode + this->vectorSize - 1);
}
}
template <class T>
T stack<T>::at(int location) {
if (location < 0 || location >= this->vectorSize) {
throw range_error("index out of range");
}
else {
return *(this->vectorNode + location);
}
}
错误提示:
出现原因
若构造的类为模板类,那么派生类不可以直接使用继承到的基类数据和方法,需要通过this指针使用。否则,在使用一些较新的编译器时,会报“找不到标识符”错误。
代码修改为
stack 类
#include "pch.h"
#include <iostream>
#include "vector.cpp"
using namespace std;
template <class T>
class stack :public vector<T> {
public:
//返回栈顶元素
T top();
private:
//修改父类at()方法的访问权限
T at(int location);
};
template <class T>
T stack<T>::top() {
if (this->vectorSize == 0) {
throw range_error("the size of vector is zero");
}
else {
return *(this->vectorNode + this->vectorSize - 1);
}
}
template <class T>
T stack<T>::at(int location) {
if (location < 0 || location >= this->vectorSize) {
throw range_error("index out of range");
}
else {
return *(this->vectorNode + location);
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)