此程序旨在將羅馬數字轉換爲等效的十進制數字。我理解下面的代碼中的邏輯不是靠近需要正常工作的地方。但是,我只是試圖在處理算法之前正確設置類成員,並且在引用定義爲字符串類型的私有成員romanNumeral時出現語法錯誤。以下顯示我的代碼以及我收到的錯誤消息。類中的字符串成員變量的語法錯誤
頭文件 - roman.h
class romanType
{
public:
void storeRoman();
void convertRoman();
void printRoman();
romanType();
private:
string romanNumeral;
int decimal;
};
Implamentation文件 - romanImp.cpp
#include <iostream>
#include <string>
#include "roman.h"
using namespace std;
void romanType::storeRoman()
{
// Promt user to enter roman numeral and store
// in romanNumeral variable member
cout << "Please enter a Roman Numeral: ";
getline(cin, romanNumeral);
// Input Validation
}
void romanType::convertRoman()
{
// When function is called, decimal starts at zero
decimal = 0;
for (int index = 0; index < romanNumeral.size(); index++)
{
switch (romanNumeral[index])
{
case 'M':
decimal += 1000;
break;
case 'D':
decimal += 500;
break;
case 'C':
decimal += 100;
break;
case 'L':
decimal += 50;
break;
case 'X':
decimal += 10;
break;
case 'V':
decimal += 5;
break;
case 'I':
decimal += 1;
break;
}
}
}
void romanType::printRoman()
{
// Print roman numeral
cout << "The Roman Numeral entered was: " << romanNumeral << endl;
// Print deciaml
cout << "This converts to " << decimal << " in decimal." << decimal << endl;
}
romanType::romanType()
{
romanNumeral = "I";
decimal = 1;
}
主源文件
// Project 4
#include <iostream>
#include <string>
#include "roman.h"
using namespace std;
int main()
{
romanType testRoman;
// Display default constructor values
testRoman.printRoman();
// Run program
testRoman.storeRoman();
testRoman.convertRoman();
testRoman.printRoman();
return 0;
}
錯誤消息:
錯誤C2146:語法錯誤:缺少';'在標識符'romanNumeral'之前 錯誤C4430:缺少類型說明符 - 假定爲int。注意:C++不支持默認int 錯誤C2065:romanNumeral「:未聲明的標識符
您是否在'roman.h文件中放置了'using namespace std;'?如果不是的話,那麼將'string romanNumeral;'更改爲'std :: string romanNumeral;' –
@JimmyThompson,我甚至不會提到使用using指令的選項。把這些放在標題中是邪惡的。 – chris
@chris當然,我只是在閱讀錯誤信息不好,所以我不得不問。這就是爲什麼我建議將其更改爲'std :: string'而不是簡單地添加'using'指令。 –