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; //明顯的定義錯,后面的應(yīng)該*last,,否則type* t = frist; 無法通過編譯 2,。type operator[](int ind) 必須有返回值,后面可加 return t; 3,。你的列表沒有初始化(沒有缺省的棧頂空間),,會導(dǎo)致 type operator[](int ind) 中內(nèi)存溢出的 4.next作為關(guān)鍵字,不要用它做標(biāo)識符(這個是最基礎(chǔ)的了)