简体   繁体   English

如何在 c++ 中使用带有函数的枚举?

[英]How do I use enums with functions in c++?

I am trying to write a function GetSex() that sets an enum value, Sex , and prints it to the console in C++ using a value from an external.txt file but I am getting all sorts of compile errors due to incorrect syntax.我正在尝试编写一个 function GetSex()来设置枚举值Sex ,并使用来自 external.txt 文件的值将其打印到 C++ 中的控制台,但由于语法不正确,我收到了各种编译错误。

What do I have wrong here?我在这里有什么问题?

Code:代码:

Sex GetSex(fstream&); //function prototype
enum Sex {M, F}; 

int main()
{
    fstream inStream("InputText.txt"); //create fstream object
    Sex mySex;  // create enum object
    mySex = GetSex(inStream); 
    cout << "Sex of first person is " << mySex;
    return 0;
}

Sex GetSex(fstream& inStream)
{
   //read in next letter in file
    char sexChar;
    inStream.get(sexChar);

    // set enum from char
    Sex mySex = static_cast<Sex>(sexChar);
    return mySex;
}

InputText.txt contains single chars each on a new line indicating the sex of a person: InputText.txt 包含单个字符,每个字符都在一个新的行上,表示一个人的性别:

M
F
M
F

Errors:错误:

error C4430: missing type specifier - int assumed.错误 C4430:缺少类型说明符 - 假定为 int。 Note: C++ does not support default-int注意:C++ 不支持 default-int

(10,5): error C2146: syntax error: missing ';' (10,5):错误 C2146:语法错误:缺少 ';' before identifier 'GetSex'在标识符“GetSex”之前

(21,9): error C2146: syntax error: missing ';' (21,9):错误 C2146:语法错误:缺少 ';' before identifier 'mySex'在标识符“mySex”之前

(21,9): error C2065: 'mySex': undeclared identifier (21,9): 错误 C2065: 'mySex': 未声明的标识符

(22,5): error C2065: 'mySex': undeclared identifier (22,5): 错误 C2065: 'mySex': 未声明的标识符

(22,13): error C3861: 'GetSex': identifier not found (22,13): 错误 C3861: 'GetSex': 找不到标识符

(23,42): error C2065: 'mySex': undeclared identifier (23,42): 错误 C2065: 'mySex': 未声明的标识符

(42,11): error C4430: missing type specifier - int assumed. (42,11):错误 C4430:缺少类型说明符 - 假定为 int。 Note: C++ does not support default-int注意:C++ 不支持 default-int

(42,1): error C2086: 'int Sex': redefinition (42,1): 错误 C2086: 'int Sex': 重新定义

(10): message: see declaration of 'Sex' (10): 消息:见“性”声明

(42,5): error C2146: syntax error: missing ';' (42,5):错误 C2146:语法错误:缺少 ';' before identifier 'GetSex'在标识符“GetSex”之前

(43,1): error C2143: syntax error: missing ';' (43,1):错误 C2143:语法错误:缺少 ';' before '{'前 '{'

(43,1): error C2447: '{': missing function header (old-style formal list?) (43,1): 错误 C2447: '{': 缺少 function header (旧式正式列表?)

You'll have to write some sort of conversion function.您必须编写某种转换 function。 Something like:就像是:

std::optional<Sex> CharToSex(char c) {
    switch (c) {
        case 'M':
        case 'm':
            return Sex::M;
        case 'F':
        case 'f': 
            return Sex::F;
        default:
            return std::nullopt;
    }
}

If you don't like std::optional then you could use an exception instead.如果您不喜欢std::optional那么您可以使用异常来代替。

You'll also have to declare CharToSex above where you use it but that's not relevant to your question.您还必须在使用它的地方声明 CharToSex ,但这与您的问题无关。

Your compiler error specifically is due to Sex not being known in GetSex()您的编译器错误具体是由于在 GetSex() 中不知道 Sex

Just swap around the enum definition and function declaration.只需交换枚举定义和 function 声明即可。

After moving enum Sex {M, F};移动后enum Sex {M, F}; above the function declaration, and adding the missing includes and using namespace std;在 function 声明之上,并添加缺少的 include 和using namespace std; , I get no errors. ,我没有错误。

But still, Sex mySex = static_cast<Sex>(sexChar);但是, Sex mySex = static_cast<Sex>(sexChar); doesn't do what you think it does.不做你认为它做的事。 There's no built-in way to convert a string (or a character) to a enum.没有将字符串(或字符)转换为枚举的内置方法。 (See the other answer for how it can be done.) (有关如何完成,请参阅其他答案。)

Instead, this line treats sexChar as a numeric value, and creates a Sex with that numeric value.相反,此行将sexChar视为一个数值,并使用该数值创建一个Sex static_cast<Sex>(0) would give you M , and static_cast<Sex>(1) would give you F . static_cast<Sex>(0)会给你M ,而static_cast<Sex>(1)会给你F Casting any other number to Sex causes undefined behavior.将任何其他数字转换为Sex会导致未定义的行为。 (In some cases it's allowed to cast a number to a enum even if it doesn't have a constant with that value, but it doesn't apply here; you can find more details at cppreference ). (在某些情况下,即使它没有具有该值的常量,也允许将数字转换为枚举,但它不适用于此处;您可以在cppreference找到更多详细信息)。

Replace:代替:

Sex GetSex(fstream&);
enum Sex { M, F };

in:在:

enum Sex { M, F };
Sex GetSex(fstream&);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM