函数参数过多

5

我从头文件中得到了这个错误: too many arguments to function void printCandidateReport();。我对C++相当新,只需要一些指导来解决这个错误。

我的头文件如下:

#ifndef CANDIDATE_H_INCLUDED
#define CANDIDATE_H_INCLUDED

// Max # of candidates permitted by this program
const int maxCandidates = 10;

// How many candidates in the national election?
int nCandidates;

// How many candidates in the primary for the state being processed
int nCandidatesInPrimary;

// Names of the candidates participating in this state's primary
extern std::string candidate[maxCandidates];

// Names of all candidates participating in the national election
std::string candidateNames[maxCandidates];

// How many votes wone by each candiate in this state's primary
int votesForCandidate[maxCandidates];

void readCandidates ();
void printCandidateReport ();
int findCandidate();
#endif

以及调用该头文件的文件:

#include <iostream>
#include "candidate.h"
/**
* Find the candidate with the indicated name. Returns the array index
* for the candidate if found, nCandidates if it cannot be found.
*/
int findCandidate(std::string name) {
    int result = nCandidates;
    for (int i = 0; i < nCandidates && result == nCandidates; ++i)
        if (candidateNames[i] == name)
            result = i;
    return result;
}

/**
* Print the report line for the indicated candidate
*/
void printCandidateReport(int candidateNum) {
    int requiredToWin = (2 * totalDelegates + 2) / 3; // Note: the +2 rounds up
    if (delegatesWon[candidateNum] >= requiredToWin)
        cout << "* ";
    else
        cout << "  ";
    cout << delegatesWon[candidateNum] << " " << candidateNames[candidateNum]
         << endl;
}

/**
* read the list of candidate names, initializing their delegate counts to 0.
*/
void readCandidates() {
    cin >> nCandidates;
    string line;
    getline(cin, line);

    for (int i = 0; i < nCandidates; ++i) {
        getline(cin, candidateNames[i]);
        delegatesWon[i] = 0;
    }
}

为什么我会收到这个错误,如何修复它?
4个回答

9
在头文件中,您声明如下内容:
void printCandidateReport ();

但是在实施过程中:

void printCandidateReport(int candidateNum){...}

将头文件更改为:

void printCandidateReport(int candidateNum);

4
错误信息告诉你问题的具体所在。
在你的头文件中,你声明了没有参数的函数:
void printCandidateReport ();

在源文件中,你需要使用类型为int的参数进行定义:
void printCandidateReport(int candidateNum){

要么在声明中添加缺失的参数,要么将其从定义中删除。


我居然比你的帖子快了一秒钟,真巧! - Chantola

4

错误消息 too many arguments to function 可以通过消除函数中多余的参数来解决。

这个错误是因为您的头文件没有参数值,在实际源代码中使用了 int 参数。

您有两个选择,可以在函数声明中添加缺少的 int 参数,或者完全从函数中删除它。


2
头文件声明了不带参数的printCandidateReport()函数,而cpp文件定义了带一个int参数的这个函数。只需在头文件的函数声明中添加int参数即可解决问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接