我正在使用C++ 14並試圖爲每個循環創建一個打印出數組的每個字符串。我得到的錯誤:對於每個循環只需要第一個字符串的數組C++
user.cpp:12:34: error: invalid initialization of reference of type ‘std::string& {aka std::basic_string&}’ from expression of type ‘char’
for(std::string &str : *(u->favs)){
當我改變的std :: string自動在foreach循環中,它的工作原理,但STR爲的收藏數組中的第一個字符串的單個字符。 我的代碼如下:
user.h
class User{
private:
public:
User(){
favs = new std::string[5]{std::string("Hello"), std::string("how"), std::string("are"), std::string("you"), std::string("?")};
}
~User(){
delete[] favs;
}
std::string lName;
std::string fName;
int age;
std::string *favs;
};
user.cpp
#include <iostream>
#include "user.h"
void create(User *u){
std::cout << "Please enter first name: ";
std::cin >> u->fName;
std::cout << "Please enter last name: ";
std::cin >> u->lName;
std::cout << "Please enter age: ";
std::cin >> u->age;
for(std::string &str : *(u->favs)){
std::cout << str << std::endl;
}
std::cout << "\n";
}
的main.cpp
#include <iostream>
#include <string>
#include "user.h"
int main(){
std::string command;
User user;
std::cout << "bp1: " << user.favs->size() << std::endl;
while(true){
std::cout << "Please enter a command (Create, Update, View, Favorites, or Quit): ";
std::cin >> command;
if(command == "Create"){
create(&user);
} else if(command == "Update"){
update(&user);
} else if(command == "View"){
view(&user);
} else if(command == "Favorites"){
//favorites(&user);
} else if(command == "Quit"){
break;
} else std::cout << "Please input a valid command.\n";
}
}
此外,user.favs的大小是數組中第一個字符串的大小,而不是數組中元素的數量 – a0935