[問題] 用iterator操作一個class的問題

看板C_and_CPP (C/C++)作者 (兌現承諾)時間16年前 (2009/07/27 11:37), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串1/1
第一次使用list.想借重list插入元素後 還可以使用iterator的優點. 以下是我遇到的問題. 這是一個簡單的測試. 未來我將會在constructor內對data member做許多運算. 如果不能直接使用constructor初始化.就有一點不方便了. 謝謝你的幫忙. #include <iostream> #include <cstdlib> #include <list> using namespace std; class Arithmetic { public: int a,b; Arithmetic(int l, int m):a(l),b(m){} int Add() { return a+b; } int Subtract() { return a-b; } }; int main() { list<Arithmetic> test; list<Arithmetic>::iterator iter=test.begin(); //iter(5,2); //不能使用constructor是個大麻煩. iter->a=5; //所以iter是指標!? iter->b=2; int c=iter->Add(); cout << "c=" << c << endl; system("pause"); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.120.11.75

07/27 11:38, , 1F

07/29 11:02, , 2F
加assignment operator 然後 (*iter) = Arithmetic(5,2)
07/29 11:02, 2F
文章代碼(AID): #1ARI478l (C_and_CPP)
文章代碼(AID): #1ARI478l (C_and_CPP)