我有一个枚举
enum ft_dev_type
{
SPI_I2C,
GPIO
};
Run Code Online (Sandbox Code Playgroud)
我希望能够构造这样的字符串
std::string s = "enum =" + SPI_I2C; //would contain "enum = SPI_I2C"
Run Code Online (Sandbox Code Playgroud)
为此,我试图重载 + 运算符
std::string operator+(const ft_dev_type type) const
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到
将 'ft_dev_type' 添加到字符串不会附加到字符串。
如何正确重载 + 运算符?
[编辑] 下面是类
class driver_FT4222
{
public:
driver_FT4222() {}
enum ft_dev_type
{
SPI_I2C,
GPIO
};
std::string operator+(const ft_dev_type type) const //this line is probably wrong
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
}
void doSomething()
{
...
std::string s = "enum =" + SPI_I2C; //would contain "enum = SPI_I2C"
std::cout <<s;
...
}
}
Run Code Online (Sandbox Code Playgroud)
看来您想要免费功能:
std::string operator+(const char* s, const ft_dev_type type)
{
switch (type)
{
case SPI_I2C: return s + std::string("SPI_I2C");
case GPIO: return s + std::string("GPIO");
}
throw std::runtime_error("Invalid enum value");
}
Run Code Online (Sandbox Code Playgroud)
(和类似的std::string...)
但更好的 IMO 有一个 to_string
std::string to_string(const ft_dev_type type)
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
throw std::runtime_error("Invalid enum value");
}
Run Code Online (Sandbox Code Playgroud)
具有
std::string s = "enum =" + to_string(SPI_I2C);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39 次 |
| 最近记录: |