c++ - 无法转换参数错误

标签 c++ visual-c++

我的程序在最后使用 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/

相关文章:

c++ - static_cast<std::u16string> 的 GCC 问题

c++ - 为什么用c_str()转换路径类型后opendir()不打开路径?

c++ - 新的空 VC++ 控制台项目缺少 MFC71.DLL

c++ - 难以计算圆上一点的角度

c++ - Windows API 和字符串连接

visual-c++ - <msbuild/> 任务失败而 <devenv/> 在 CruiseControl.NET 中的 MFC 应用程序成功?

c++ - C++的整数参数

c++ - 使用智能指针为大量对象创建多个索引

c++ - SmartPTR实现heap->isValid断言

c++ - 返回在 main() 函数之外创建的对象的地址