【问题标题】:defining operator + for double and string data types in cpp在 cpp 中为 double 和 string 数据类型定义运算符 +
【发布时间】:2020-12-01 04:25:05
【问题描述】:

我正在尝试使用以下函数为字符串和双精度定义运算符 +

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" 隐式转换为字符串?

【问题讨论】:

  • 好吧,因为 char * 不是字符串
  • 而且你最好接受你的 double 值,字符串 const 引用
  • @pm100:存在从const char *std::string 的隐式转换。好的答案是为什么它不能在这里使用。
  • 试试std::string operator+(const double b, std::string_view a) { return std::to_string(b) + std::string(a); } std::string test = c + "sff"s;
  • @pm100 这不是一条有用的评论。

标签: c++ operator-overloading operator-keyword explicit-conversion


【解决方案1】:

根据 C++ 17 标准(16.3.1.2 表达式中的运算符)

1 如果表达式中没有运算符的操作数的类型为 类或枚举,运算符被假定为内置 运算符并根据第 8 条进行解释。

在这个表达式中

c+"sff"

(其中cdouble 类型的标量值)操作数都没有类或枚举类型,并且没有定义用于类型doubleconst char * 的内置运算符+。当第二个操作数为整数类型时,就定义了指针算法。

【讨论】:

  • 也可以使用结构(除了类,枚举)允许添加。 IOW,我的答案正确吗?有人投了票,但没有说明原因。
  • @anki,C++标准中的class通常指structclass
猜你喜欢
  • 2015-12-14
  • 2021-01-29
  • 2014-04-27
  • 2014-09-08
  • 1970-01-01
  • 2016-01-26
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
相关资源
最近更新 更多