2013-12-13 66 views
1

此程序旨在將羅馬數字轉換爲等效的十進制數字。我理解下面的代碼中的邏輯不是靠近需要正常工作的地方。但是,我只是試圖在處理算法之前正確設置類成員,並且在引用定義爲字符串類型的私有成員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「:未聲明的標識符

+0

您是否在'roman.h文件中放置了'using namespace std;'?如果不是的話,那麼將'string romanNumeral;'更改爲'std :: string romanNumeral;' –

+2

@JimmyThompson,我甚至不會提到使用using指令的選項。把這些放在標題中是邪惡的。 – chris

+0

@chris當然,我只是在閱讀錯誤信息不好,所以我不得不問。這就是爲什麼我建議將其更改爲'std :: string'而不是簡單地添加'using'指令。 –

回答

2

在你的roman.h文件中,你不包含字符串類,所以我認爲那是至少有一個錯誤會消失的地方。這裏是我用來讓它在代碼塊中編譯的代碼

#ifndef ROMAN_H 
#define ROMAN_H 
#include <string> 

class romanType 
{ 

public: 
    void storeRoman(); 
    void convertRoman(); 
    void printRoman(); 
    romanType(); 

private: 
    std::string romanNumeral; 
    int decimal; 

}; 

#endif // ROMAN_H 
+0

請注意,std :: string字符串位於std名稱空間中,並且還需要按順序包含正確編譯的所有內容。 – MrJman006

0

添加#include <string>roman.h頂部,在類聲明中使用std::string代替string

+0

添加此代碼工作。我不認爲這是必要的頭文件,但我想我錯了。非常感謝 –