<变量/函数>的多重定义

发布于 2024-12-03 04:27:49 字数 5845 浏览 0 评论 0 原文

我正在尝试使用candidate.h 文件、candidate.cpp 文件和main.cpp 文件编写一个基本程序,

我在candidate.h 文件中声明了一个函数void readCandidates()

然后,我在 Candidate.cpp 中将其定义为

void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

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

变量 nCandidates、candidateNames[] 和 delegatesWon[] 也都在 Candidate.h 中声明。

我还在

#ifndef CANDIDATE_H
#def CANDIDATE_H
...
#endif 

候选文件中确保它不会被定义两次。

当我运行命令 make main 时,出现错误

/home/pmurray/cs250/Asst1/primaries.cpp:33: multiple definition of `candidate'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:8: first defined here
primaries.o: In function `assignDelegatesToCandidates()':
/home/pmurray/cs250/Asst1/primaries.cpp:37: multiple definition of `nCandidates'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:15: first defined here
primaries.o: In function `assignDelegatesToCandidates()':
/home/pmurray/cs250/Asst1/primaries.cpp:38: multiple definition of `delegatesWon'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:16: first defined here
candidates.o: In function `readCandidates()':

我尝试将 extern 放在变量之一的声明之前,这导致了错误

candidates.cpp:(.text+0x49): undefined reference to `candidateNames'
primaries.o: In function `findCandidate(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
primaries.cpp:(.text+0x120): undefined reference to `candidateNames'
primaries.o: In function `printCandidateReport(int)':
primaries.cpp:(.text+0x1d8): undefined reference to `candidateNames' 

有人知道我做错了什么吗?

候选人.cpp

#include <iostream>

using namespace std;
#include "candidates.h"

void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

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

候选人.h

#ifndef CANDIDATES_H
#define CANDIDATES_H

#include <iostream>
#include <string>

using namespace std;

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

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

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

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

// How many delgates have been won by each candidate
extern int delegatesWon[maxCandidates];

extern int findCandidate (std::string name);


/**
 * read the list of candidate names, initializing their delegate counts to 0.
 */
void readCandidates ();

#endif // CANDIDATES_H

primaries.cpp (这是我的 main.cpp)

#include <iostream>
//#include "candidates.cpp"

using namespace std;

#include "candidates.h"

// How many delegates are assigned to the state being processed
int delegatesForThisState;

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

// How many states participate in the election
int nStates;

// How many delegates in the election (over all states)
int totalDelegates = 0;

// How many votes were cast in the primary for this state
int totalVotes;

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


/**
 * For the most recently read primary, determine how many delegates have
 * been won by each candidate.
 */
int assignDelegatesToCandidates ()
{
  int remainingDelegates = delegatesForThisState;
  for (int i = 0; i < nCandidatesInPrimary; ++i)
    {
      int candidateNum = findCandidate(candidate[i]);
      int nDel = (delegatesForThisState * votesForCandidate[i] + (totalVotes-1)) / totalVotes;
      if (nDel > remainingDelegates)
    nDel = remainingDelegates;
      delegatesWon[candidateNum] += nDel;
      remainingDelegates -= nDel;
    }
}



/**
 * 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
 */
int 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 info on one state's primaries
 */
void readState ()
{
  totalVotes = 0;
  cin >> nCandidatesInPrimary >> delegatesForThisState;
  totalDelegates += delegatesForThisState;  // "x += y" is a shorthand for "x = x + y"
  string word, line;
  getline (cin, line);
  for (int i = 0; i < nCandidatesInPrimary; ++i)
    {
      cin >> votesForCandidate[i];
      totalVotes = totalVotes + votesForCandidate[i];

      cin >> word;
      getline (cin, line);
      candidate[i] = word + line;
    }
}



/**
 * Generate the report on the national primary election.
 */
int main(int argc, char** argv)
{
  readCandidates();
  int nStates;
  cin >> nStates;
  for (int i = 0; i < nStates; ++i)
    {
      readState();
      assignDelegatesToCandidates();
    }
  for (int i = 0; i < nCandidates; ++i)
    {
      printCandidateReport(i);
    }
  return 0;
}

I am trying to write a basic program with a candidate.h file, a candidate.cpp file, and a main.cpp file

I declared a function void readCandidates() in my candidate.h file.

I then define it in candidate.cpp as

void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

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

The variables nCandidates, candidateNames[] and delegatesWon[] are all declared in candidate.h as well.

I also have

#ifndef CANDIDATE_H
#def CANDIDATE_H
...
#endif 

in my candidate.h file to ensure that it doesn't get defined twice.

When I run the command make main I get the error

/home/pmurray/cs250/Asst1/primaries.cpp:33: multiple definition of `candidate'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:8: first defined here
primaries.o: In function `assignDelegatesToCandidates()':
/home/pmurray/cs250/Asst1/primaries.cpp:37: multiple definition of `nCandidates'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:15: first defined here
primaries.o: In function `assignDelegatesToCandidates()':
/home/pmurray/cs250/Asst1/primaries.cpp:38: multiple definition of `delegatesWon'
candidates.o:/home/pmurray/cs250/Asst1/candidates.cpp:16: first defined here
candidates.o: In function `readCandidates()':

I tried putting extern before the declaration of one of the variables, and that resulted in the error

candidates.cpp:(.text+0x49): undefined reference to `candidateNames'
primaries.o: In function `findCandidate(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
primaries.cpp:(.text+0x120): undefined reference to `candidateNames'
primaries.o: In function `printCandidateReport(int)':
primaries.cpp:(.text+0x1d8): undefined reference to `candidateNames' 

Anyone know what I am doing wrong?

candidates.cpp

#include <iostream>

using namespace std;
#include "candidates.h"

void readCandidates ()
{
  cin >> nCandidates;
  string line;
  getline (cin, line);

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

candidates.h

#ifndef CANDIDATES_H
#define CANDIDATES_H

#include <iostream>
#include <string>

using namespace std;

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

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

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

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

// How many delgates have been won by each candidate
extern int delegatesWon[maxCandidates];

extern int findCandidate (std::string name);


/**
 * read the list of candidate names, initializing their delegate counts to 0.
 */
void readCandidates ();

#endif // CANDIDATES_H

primaries.cpp (which is my main.cpp)

#include <iostream>
//#include "candidates.cpp"

using namespace std;

#include "candidates.h"

// How many delegates are assigned to the state being processed
int delegatesForThisState;

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

// How many states participate in the election
int nStates;

// How many delegates in the election (over all states)
int totalDelegates = 0;

// How many votes were cast in the primary for this state
int totalVotes;

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


/**
 * For the most recently read primary, determine how many delegates have
 * been won by each candidate.
 */
int assignDelegatesToCandidates ()
{
  int remainingDelegates = delegatesForThisState;
  for (int i = 0; i < nCandidatesInPrimary; ++i)
    {
      int candidateNum = findCandidate(candidate[i]);
      int nDel = (delegatesForThisState * votesForCandidate[i] + (totalVotes-1)) / totalVotes;
      if (nDel > remainingDelegates)
    nDel = remainingDelegates;
      delegatesWon[candidateNum] += nDel;
      remainingDelegates -= nDel;
    }
}



/**
 * 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
 */
int 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 info on one state's primaries
 */
void readState ()
{
  totalVotes = 0;
  cin >> nCandidatesInPrimary >> delegatesForThisState;
  totalDelegates += delegatesForThisState;  // "x += y" is a shorthand for "x = x + y"
  string word, line;
  getline (cin, line);
  for (int i = 0; i < nCandidatesInPrimary; ++i)
    {
      cin >> votesForCandidate[i];
      totalVotes = totalVotes + votesForCandidate[i];

      cin >> word;
      getline (cin, line);
      candidate[i] = word + line;
    }
}



/**
 * Generate the report on the national primary election.
 */
int main(int argc, char** argv)
{
  readCandidates();
  int nStates;
  cin >> nStates;
  for (int i = 0; i < nStates; ++i)
    {
      readState();
      assignDelegatesToCandidates();
    }
  for (int i = 0; i < nCandidates; ++i)
    {
      printCandidateReport(i);
    }
  return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不一样的天空 2024-12-10 04:27:49

你在头文件中声明变量和函数 extern ,你仍然需要在某个地方定义它们,最好在使用它们的 .cpp 文件中(candidates.cpp 在你的情况下)。

将您在函数中使用的所有变量的定义添加到您的 candidates.cpp 文件中,这将解决您的问题。

顺便说一句,同意这不是一个好的编程形式,但这可能超出了这个问题的范围。您不需要全局变量,因为不需要在实现文件 (.cpp) 之外访问它们。

You declare variables and functions extern in header file, you still need to define them somewhere, the best in the .cpp file where you use them (candidates.cpp in your case).

Add to your candidates.cpp file the definitions of all those variables that you are using in your functions, that will fix your problem.

Btw, agreed that this is not a good programming form, but that is probably outside of the scope of this question. You should not need global variables because they don't need to be accessed outside of the implementation file (.cpp).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文