因此,對於課程,我必須編寫一個模擬賽馬的程序。這是我們第一個涉及課程的重大項目。我被卡在主題中提到的錯誤。現在,自引入它們以來,我一直在與指針進行鬥爭,所以我毫不懷疑這是我的總體問題所在。我已經請教過我的教授,但他沒有回覆我的電子郵件。我也聯繫過朋友等,沒有人回到我身邊。C++:錯誤'std :: string'是私人的
這是我的頭文件(Horse.h):
#ifndef HORSE_H
#define HORSE_H
#include <string>
class Horse
{
private:
std::string name;
std::string jockey;
int maxSpeed;
int distanceTraveled;
int racesWon;
public:
Horse(std::string, std::string);
void runOneSecond(int);
void sendToGate();
void displayHorse (double);
};
#endif // HORSE_H
這裏是我的Horse.cpp:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include "Horse.h"
using namespace std;
Horse::Horse(string name, string jockey)
{
srand (time(NULL));
int maxSpeed = rand() % 30 + 1;
distanceTraveled = 0;
};
void Horse::runOneSecond(int maxSpeed)
{
srand (time(NULL));
distanceTraveled = rand() % maxSpeed;
};
void Horse::sendToGate()
{
distanceTraveled = 0;
};
void Horse::displayHorse(double raceDistance)
{
int percentage;
for (int i = 0; i < numberOfHorses; i++)
{
cout << "|";
}
};
這裏是我的main.cpp:
#include <iostream>
#include <string>
#include <cctype>
#include "Horse.h"
using namespace std;
int main()
{
double raceDistance = 0;
int numberOfHorses = 0;
char choice = 'Y';
string name;
string jockey;
cout << "Enter the number of horses for the race: ";
cin >> numberOfHorses;
Horse** horsePtr = new Horse* [numberOfHorses];
// Trouble section.
for (int i = 0; i < numberOfHorses; i++)
{
cout << "Fill in the name of the horse: ";
cin >> horsePtr[i]->name;
cout << "Fill in the name of the jockey: ";
cin >> horsePtr[i]->jockey;
}
cout << "How long should the race be (in meters): ";
cin >> raceDistance;
cout << endl;
cout << "Start!" << endl;
for (int i = 0; i < numberOfHorses; i++)
{
horsePtr[i]->sendToGate();
}
for (int i = 0; i < numberOfHorses; i++)
{
horsePtr[i]->displayHorse(raceDistance);
}
cout << "Show the next second of the race? ";
cin >> choice;
while(toupper(choice) == 'Y')
{
if (toupper(choice) == 'Y')
{
for (int i = 0; i < numberOfHorses; i++)
{
horsePtr[i]->runOneSecond(maxSpeed);
horsePtr[i]->displayHorse(raceDistance);
}
}
}
return 0;
}
以下是錯誤:
Horse.cpp: In member function ‘void Horse::displayHorse(double)’:
Horse.cpp:29:23: error: ‘numberOfHorses’ was not declared in this scope
for (int i = 0; i < numberOfHorses; i++)
^
In file included from main.cpp:4:0:
Horse.h: In function ‘int main()’:
Horse.h:8:17: error: ‘std::string Horse::name’ is private
std::string name;
^
main.cpp:25:25: error: within this context
cin >> horsePtr[i]->name;
^
In file included from main_dmj8t6.cpp:4:0:
Horse.h:9:17: error: ‘std::string Horse::jockey’ is private
std::string jockey;
^
main.cpp:27:25: error: within this context
cin >> horsePtr[i]->jockey;
^
main.cpp:55:35: error: ‘maxSpeed’ was not declared in this scope
horsePtr[i]->runOneSecond(maxSpeed);
^
如果錯誤的行怎麼辦? –
你應該只調用'srand'一次。你也可以找到'std :: vector'比指針更容易使用。 'cin >> horsePtr [i] - > name;'這是不正確的,因爲你還沒有在那裏分配任何Horse對象。 –
'我<&numberOfHorses'你爲什麼要拿着'numberOfHorses'的地址? – Adam