<<C++ Primer>> 第四版Exercise Section 5.6 的5.1.6 有一道題是這樣的:編寫程序定義一個vector對象,其每個元素都是指向string類型的指針,讀取vector對象並輸出每個string類型的值以及其長度。
1 // 2_3.cpp : 定義控制台應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <string> 7 #include <vector> 8 #include <ctime> 9 10 using namespace std; 11 12 int main() 13 { 14 vector<string*> vect; 15 string str = "hello"; 16 string str1 = "world"; 17 vect.push_back(&str); 18 vect.push_back(&str1); 19 20 for (vector<string*>::iterator begin = vect.begin(); begin != vect.end(); ++begin) 21 { 22 cout << *(*begin) << endl; 23 cout << (*begin)->length() << endl; 24 } 25 26 return 0; 27 }
其實這里想要考查的是,通過指針獲取對象的成員函數可以使用-> 操作符。