【发布时间】:2015-06-06 02:13:09
【问题描述】:
这里是菜鸟,
我正在尝试从 Bjarne Stroustrup 的“C++ 编程语言”编译这段代码,但 CodeBlocks 不断向我抛出此错误。
代码是关于检查向量函数中保存的数组的范围。
代码如下:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
int i = 1000;
template<class T> class Vec : public vector<T>
{
public:
Vec() : vector<T>() { }
T& operator[] (int i) {return at(i); }
const T& operator[] (int i) const {return at(i); }
//The at() operation is a vector subscript operation
//that throws an exception of type out_of_range
//if its argument is out of the vector's range.
};
Vec<Entry> phone_book(1000);
int main()
{
return 0;
}
返回的错误是:
- “at”没有依赖于模板参数的参数,因此“at”的声明必须可用
- 注意:(如果您使用“-fpermissive”,G++ 将接受您的代码,但不允许使用未声明的名称
- 在成员函数'const T& operator[] (int i) const'中:
- “at”没有依赖于模板参数的参数,因此“at”的声明必须可用
- “条目”未在此范围内声明
- 模板参数 1 无效
- '('标记之前的声明类型无效
谁能给我解释一下?
另外,如果我不使用'using namespace std;',我将如何实现它
【问题讨论】:
-
从 stl 容器继承时,您应该知道它们没有虚拟析构函数。当您的子类获取应该在其析构函数中释放的资源时,这可能会导致问题。
-
最后一个问题很简单:要么在每个来自
namespace std的名字前面写上std::,例如到处写std::vector,或者写一次using std::vector(而不是namespace,只列出你使用的所有个人名字) -
这个错误的 MSVC++ 版本是“函数声明必须可用,因为没有任何参数依赖于模板参数”
标签: c++ templates vector compiler-errors std