此程序旨在将罗马数字转换为等效的十进制数。我了解以下代码中的逻辑离正常运行所需的位置不远。但是,我只是试图在处理算法之前正确设置类成员,并且在引用定义为字符串类型的私有(private)成员 romanNumeral 时遇到语法错误。下面显示了我的代码以及我收到的错误消息。
头文件 - roman.h
class romanType
{
public:
void storeRoman();
void convertRoman();
void printRoman();
romanType();
private:
string romanNumeral;
int decimal;
};
实现文件 - 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++ 不支持 default-int 错误 C2065:“romanNumeral”:未声明的标识符
最佳答案
在您的 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
关于c++ - 类中字符串成员变量的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20573389/