[問題] vector 在 class 裡面使用

看板C_and_CPP (C/C++)作者 (風)時間14年前 (2012/04/19 22:20), 編輯推噓1(1017)
留言18則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) NetBeans 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) vector 問題(Question): 無法compile 錯誤結果(Wrong Output): main.cpp:22: error: no matching function for call to `std::vector<int, std::allocator<int> >::pop_back(int)' /usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_vector.h:578: note: candidates are: void std::vector<_Tp, _Alloc>::pop_back() [with _Tp = int, _Alloc = std::allocator<int>] 程式碼(Code):(請善用置底文網頁, 記得排版) # include <stdlib.h> # include <stdio.h> # include <iostream> # include <vector> using namespace std; class Test { public: vector<int> num; Test():num(5) { } }; int main() { Test test; test.num.pop_back( 5 ); system( "pause" ); } // main() 補充說明(Supplement): 想在class裡面用 vector 可是不知道怎樣在 main 裡面做存取 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.204.79.140

04/19 22:33, , 1F
pop_back()不是這樣用,它不需要參數
04/19 22:33, 1F

04/19 22:35, , 2F
如果需要刪除vector裡的元素要用erase和iterator
04/19 22:35, 2F

04/19 22:37, , 3F
那如果不在 class 裡面設初始大小也可以嗎
04/19 22:37, 3F

04/19 22:40, , 4F
test.num.resize(10);
04/19 22:40, 4F

04/19 22:41, , 5F
test.num(2) = 5; // 這樣也不行@@
04/19 22:41, 5F

04/19 22:49, , 6F
test.num[2] = 5
04/19 22:49, 6F

04/19 22:59, , 7F
感謝@@ 耍笨了
04/19 22:59, 7F

04/19 23:16, , 8F
如果把 vector 宣告成 static 的話, 要如何使用?
04/19 23:16, 8F

04/19 23:29, , 9F
例如我把 vector 前面加上 static
04/19 23:29, 9F

04/19 23:29, , 10F
然後再 main 裡面印出 Test::num.capacity()
04/19 23:29, 10F

04/19 23:30, , 11F
[Linker error] undefined reference to `Test::num'
04/19 23:30, 11F

04/19 23:31, , 12F
我知道在 class 裡面的變數加 static 是整個class共
04/19 23:31, 12F

04/19 23:31, , 13F
用一份 可是不知道怎存取 vector 這種的...
04/19 23:31, 13F

04/20 00:14, , 14F
不要用建構初始
04/20 00:14, 14F

04/20 08:42, , 15F
那要怎避免以上的Linker error
04/20 08:42, 15F

04/20 10:19, , 16F
static member 要在class外定義
04/20 10:19, 16F

04/20 17:22, , 17F
可以舉例嗎??
04/20 17:22, 17F

04/20 22:41, , 18F
04/20 22:41, 18F
文章代碼(AID): #1Fa1ytKj (C_and_CPP)
文章代碼(AID): #1Fa1ytKj (C_and_CPP)