[問題] (已解)繼承vector覆寫operator[]的問題

看板C_and_CPP (C/C++)作者 ( bdvstg)時間12年前 (2013/09/14 09:51), 編輯推噓3(308)
留言11則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC10 (VC2010) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) No 問題(Question): 編譯錯誤,錯誤訊息如下 ClCompile: eVector.cpp c:\work_tmp\evector\evector\evector.cpp(32): error C2143: 語法錯誤 : 遺漏 ';' (在 'std::evector<_Ty>::[]' 之前) c:\work_tmp\evector\evector\evector.cpp(32): error C4430: 遺漏型別規範 - 假設為 int。注意: C++ 不支援 default-int 看起來似乎是不認得 reference 之前我全部inline到.h檔裡,不分.h和.cpp卻是可以Work的 現在想把宣告跟實作分開卻編譯不能... 程式碼(Code):(請善用置底文網頁, 記得排版) 全部共分兩個檔案(.h與.cpp) evector.h http://codepad.org/6x99O7L4 #ifndef __eVector_H__ #define __eVector_H__ #include <vector> namespace std { template<class _Ty> class evector : public vector<_Ty> { public: reference operator[](size_type _Pos); }; } #endif evector.cpp http://codepad.org/Dj0GU09f #include "eVector.h" namespace std { template<class _Ty> reference evector<_Ty>::operator[](size_type _Pos) { if(_Pos >= this->vector::size()) { assign(_Pos, _Ty()); } return this->vector::operator[](_Pos); } } 補充說明(Supplement): 其實我還有覆寫assign,不過怕會混淆問題所以沒放上來 其內容主要是判斷index有沒有爆,爆的話用push_back(_Ty())補到滿為止再賦值 已解決,底下放上改過的code evector.h http://codepad.org/NKENNUMi #ifndef EVector_H #define EVector_H #include <vector> namespace std { template<class T, class A = allocator<T> > class evector : public vector<T,A> { public: typename vector<T,A>::reference operator[](size_type _Pos); }; } #endif evector.cpp http://codepad.org/05HF8pNl #include "eVector.h" namespace std { template<class T, class A> typename vector<T,A>::reference evector<T,A>::operator[](size_type _Pos) { if(_Pos >= this->vector<T,A>::size()) { assign(_Pos, T()); } return this->vector<T,A>::operator[](_Pos); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.96.40.191

09/14 10:36, , 1F
不要繼承 STL container!這些東西設計上不允許繼承
09/14 10:36, 1F

09/14 10:45, , 2F
雖說如此 但我還是想試 目前實作也放在.h裡的話 是OK的
09/14 10:45, 2F

09/14 10:46, , 3F
雖然.h會變很亂很難看 不過用起來很方便
09/14 10:46, 3F

09/14 10:47, , 4F
但分成.cpp跟.h 分開寫 就總是編譯不過...
09/14 10:47, 4F

09/14 10:48, , 5F
你還是用 composition 的方式然後自己寫你要拉出來的函式吧
09/14 10:48, 5F

09/14 10:53, , 6F
支援分離式template的compiler很少,你還是要一起寫
09/14 10:53, 6F

09/14 10:53, , 7F
reference的地方要寫 typename vector<T>::reference
09/14 10:53, 7F

09/14 10:56, , 8F
另外,不要用 __eVector_H__ 當作 include guard
09/14 10:56, 8F

09/14 10:56, , 9F
也不要用 _Ty,原因請見 #1EjCxNm6
09/14 10:56, 9F

09/14 11:11, , 10F
喔喔喔~過了!! 還有底線的命名規則我也是第一次知道
09/14 11:11, 10F

09/14 11:11, , 11F
感恩~~
09/14 11:11, 11F
※ 編輯: bdvstg 來自: 140.96.40.191 (09/14 11:17)
文章代碼(AID): #1ICy4ktT (C_and_CPP)
文章代碼(AID): #1ICy4ktT (C_and_CPP)