以前我問過一個問題,並得到一個小答案,但現在我被帶到一個點,我無法成功地編譯此代碼。我試圖建立一個商店類型的數據庫,現在我可以簡單地使用一個字符串數組。但我建議使用字符串數組是C++中不好的做法,並不是一個好主意繼續。因此,爲了將來的參考,我希望這樣做,以便稍後我可以在考試中解決向量問題。不能轉換int向量
#include "string"
#include "vector"
#include "iostream"
using namespace std;
class shop
{
private:
int i, n, item[20];
float price[20];
std::vector<std::string> name;
public:
void input();
void output();
};
void shop::input()
{
cout << "Enter the number of items: ";
cin >> n;
name.clear();
name.push_back(n);
name.resize(n);
for(i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the name of the item: ";
cin >> name[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for(i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
cout << "Name: " << name[i] << endl << endl;
}
}
void main()
{
class shop s;
s.input();
s.output();
}
但我得到的錯誤是:
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1> Source.cpp
1>c:\users\khale_000\documents\visual studio 2013\projects\project1\project1\source.cpp(20): error C2664: 'void std::vector<std::string,std::allocator<_Ty>>::push_back(const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)' : cannot convert argument 1 from 'int' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> &&'
1> with
1> [
1> _Ty=std::string
1> ]
1> Reason: cannot convert from 'int' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
看第20行(錯誤給出)。它看起來像是將一個int推回到一個字符串向量中。由於錯誤實際上是指向該行,我建議您在發佈 – keyser
name.push_back(n); n是整數,你的向量包含std :: strings。 你可能想先轉換成字符串。 – AlexTheo
如果你還沒有閱讀[任何這些](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list),我建議你先從其中一個介紹部分。 – Zeta