问题描述
我正在尝试使用以下函数为字符串和double定义运算符+
string operator + (const double& b,const string a){
return to_string(b)+a;
}
当我执行以下操作时,效果很好
double c = 100.256;
string d = "if only";
cout<<c+d<<"\n";
但是当我传递const char而不是string时,它将引发编译错误(类型为'double'和'const char [4]'的无效操作数为二进制'operator +')
double c = 100.256;
string test = c+"sff";
为什么不会将const char []“ sff”隐式转换为字符串?
解决方法
根据C ++ 17标准(表达式中的16.3.1.2运算符)
1如果表达式中没有运算符的操作数具有以下类型: 类或枚举,则假定运算符是内置的 运算符,并根据第8条进行了解释。
在此表达式中
c+"sff"
(其中c
是类型double
的标量值)操作数都不具有类或枚举类型,并且对于类型double
和{{1 }} 没有定义。当第二个操作数具有整数类型时,将定义指针算术。
由于该运算符重载确实起作用的原因已在
中进行了解释这是一个可行的解决方案。 string_view
和const char *
版本都可以使用。
注意避免类似的陷阱
#include <iostream>
#include <string>
#include <string_view>
struct doub {
private:
double num_;
public:
doub(double c) : num_(c){};
std::string operator+(std::string_view sv)
{
return std::to_string(num_) + std::string(sv);
}
// std::string operator+(const char *arr)
// {
// return std::to_string(num_) + std::string(arr);
// }
};
int main()
{
doub c{100.256};
std::cout << c + "sff" << std::endl;
return 0;
}