简体   繁体   English

C vs C ++:如何解决? Typedef枚举

[英]C vs C++: How to fix? Typedef Enum

I have found that code that works (although with warning) in C is now giving me an error when moved to C++. 我发现在C中有效的代码(尽管有警告)现在移到C ++时给我一个错误。 I'd like to know why this produces an error, and how to resolve. 我想知道为什么会产生错误,以及如何解决。

I am converting someone elses code to C++ and this gave me the error (pulled out and tested in its own file)... 我正在将其他人的代码转换为C ++,这给了我错误(将其拉出并在其自己的文件中进行测试)...

#include <stdio.h>

typedef enum SPI_SSADDR_TYPE
{
    SSADDR0 = 0,
    SSADDR1 = 1,
    SSADDR2,
    SSADDR3,
    SSADDR4,
    SSADDR5,
    SSADDR6,
    SSADDR7,
    SSADDR8
} SPI_SSADDR;

void SPI_set_slave_addr( SPI_SSADDR slaveSelectAddr );

int main()
{
    SPI_set_slave_addr(SSADDR8);
    return 0;
}    

void SPI_set_slave_addr( SPI_SSADDR slaveSelectAddr )
{
    slaveSelectAddr = slaveSelectAddr & (SPI_SSADDR)(0x07); // This line
    printf("Test: %d\r\n", slaveSelectAddr);
    return; 
}

The error it produces is: 它产生的错误是:

TypeDef.cpp: In function ‘void SPI_set_slave_addr(SPI_SSADDR)’:
TypeDef.cpp:26: error: invalid conversion from ‘int’ to ‘SPI_SSADDR’

In C++, unlike in C, you can't implicitly convert an integer type into an enumeration type. 与C语言不同,在C ++中,您不能将整数类型隐式转换为枚举类型。 The result of the expression is an integer type, since enumerations are converted to integers when you perform arithmetic on them, and so must be explicitly converted back: 表达式的结果是整数类型,因为枚举在对它们执行算术运算时会转换为整数,因此必须显式转换回整数:

slaveSelectAddr = static_cast<SPI_SSADDR>(slaveSelectAddr & 0x07);

尝试这个:

slaveSelectAddr = (SPI_SSADDR)((int)slaveSelectAddr & 0x07);

Try moving the cast: 尝试移动演员表:

slaveSelectAddr = (SPI_SSADDR)(slaveSelectAddr & 0x07);

You can also use a more C++ version of the cast: 您还可以使用演员表的更多C ++版本:

slaveSelectAddr = static_cast<SPI_SSADDR>(slaveSelectAddr & 0x07);
slaveSelectAddr = static_cast<SPI_SSADDR>(static_cast<int>(slaveSelectAddr) & 0x07);

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

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