VC++报错非法的间接寻址
template<typename T>class linklist {public: struct type { type* next = 0, * last = 0; T value; type operator++() { if (next != 0) *this = *next; else { std::cerr << "遍历溢出了哈!"; terminate(); }return *this; } type operator--() { if (last != 0) *this = *last; else { std::cerr << "遍历溢出了哈!"; terminate(); }return *this; } };private: type* frist, last;public: type operator[](int ind) { type t; if (ind >= 0) { t = *frist; for (int i = 0; i<ind; i++)++t; } else { t = (*last); for (int i = ind; i > 0; i--)++t; } } void push_back(T value) { type* t = last; last = new type; last->last = t; last->value = value; } void push_front(T value) { type* t = frist; frist = new type; frist->next = t; frist->value = value; } linklist operator<<(T value) { this->push_back(value); return *this; } linklist operator>>(T value) { this->push_front(value); return *this; }};int main(){ using namespace std; linklist<int> llst; llst << 5 << 4 << 1 << 8 << 8; for (auto i = llst[0]; i.next; ++i)cout << i.value; std::cout << "Hello World! ";}//报错在第40行
程序错的太多了。。。 1。type *frist, last; //明显的定义错,后面的应该*last,否则 type* t = frist; 无法通过编译 2。type operator[](int ind) 必须有返回值,后面可加 return t; 3。你的列表没有初始化(没有缺省的栈顶空间),会导致 type operator[](int ind) 中内存溢出的 4.next作为关键字,不要用它做标识符(这个是最基础的了)
下一篇:www.***.com
上一篇:请问d选项为什么是可能