我的程序在最后使用 main 函数时运行良好,但是当我添加函数原型(prototype)并将 main 函数放在开头时,我开始遇到这些错误。
error C2664: 'getData' : cannot convert parameter 1 from 'std::string [100]' to 'std::string' No constructor could take the source type, or constructor overload resolution was ambiguous
error C2664: 'descending' : cannot convert parameter 1 from 'std::string [100]' to 'std::string' No constructor could take the source type, or constructor overload resolution was ambiguous
error C2664: 'ascending' : cannot convert parameter 1 from 'std::string [100]' to 'std::string' No constructor could take the source type, or constructor overload resolution was ambiguous
error C2664: 'output' : cannot convert parameter 1 from 'std::string [100]' to 'std::string'
没有构造函数可以采用源类型,或者构造函数重载决策不明确
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void swap(string&, string&);
void getData(string, int&);
void ascending(string, int);
void descending(string, int);
void output(string, int);
int getChoice();
int main()
{
string name[100], temp;
int item, choice;
getData(name, item);
choice = getChoice();
if (choice == 1)
ascending(name, item);
if (choice == 2)
descending(name, item);
output(name, item);
}
void swap(string& name1, string& name2)
{
string temp;
temp = name1;
name1 = name2;
name2 = temp;
}
void getData(string name[], int& item)
{
ifstream fin;
fin.open("E:\\p9.txt");
item = 0;
while (!fin.eof())
{
fin >> name[item];
item++;
}
cout << "item = " << item << endl << endl;
}
void ascending(string name[], int item)
{
for(int j=0; j<item-1; j++)
{
for(int i=0; i<item-1; i++)
if(name[i] > name[i+1])
swap(name[i], name[i+1]);
}
}
void descending(string name[], int item)
{
string temp;
for(int j=0; j<item-1; j++)
{
for(int i=0; i<item-1; i++)
if(name[i] < name[i+1])
swap(name[i], name[i+1]);
}
}
void output(string name[], int item)
{
for(int i=0; i<item; i++)
cout << name[i] << endl;
cout << endl << endl;
}
int getChoice()
{
int choice;
cout << "Please enter 1 for ascending or 2 for descending." << endl;
cin >> choice;
return choice;
}
最佳答案
好吧,您的“原型(prototype)”与您的函数定义不匹配。为什么要引入与实际功能无关的原型(prototype)?
举个例子
void getData(string, int&);
void getData(string name[], int& item) { ... }
在这种情况下正确的“原型(prototype)”是
void getData(string[], int&);
关于c++ - 无法转换参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13639887/