先看幾段代碼:
1 string str1 ("aaaaaaaaaa"); 2 for(auto it1 = str1.begin(); it1 != str1.end() && !str1.empty(); ++it1 ) { 3 *it1 = toupper(*it1); 4 } 5 6 string str1 ("aaaaaaaaaa"); 7 for(auto it = str1.begin(); it != str1.end() && !it->empty(); ++it ) { //error1 8 *it1 = toupper(*it1); 9 } 10 11 vector<string> vstr{"aaa","bbb","ccc"};
13 for (auto it = vstr.begin(); it != vstr.end() && !it->empty(); ++it) { 14 *it = toupper(*it); //error2 15 }
Error1:第7行:expression must have pointer-to-class type
意思是:it->empty()這個表達式的i必須是要指向一個類的指針。it解引用后為char,是一個基本數據類型,不是類,也不存在有empty方法。
string在c++中可以是一個封裝號的字符串類。
Error2:第14行:no instance of overloaded function "toupper" matches the argument list
toupper里面處理的是字符,而it = vstr.begin(), it指向的容器Vstr里面的第一個元素即字符串。