可以将运算符*重载为int和char*的倍数

Possible to overload operator* to multiple an int and a char*?

本文关键字:char int 运算符 重载      更新时间:2023-10-16

我想获得功能,这样我就可以做到这一点:

std::cout << "here's a message" << 5*"n";

我尝试了以下方法:

std::string operator* (int lhs, const char* rhs) {
  std::string r = "";
  for(int i = 0; i < lhs; i++) {
    r += rhs;
  }
  return r;
}

我收到了一条错误消息:

error: ‘std::string operator*(int, const char*)’ must have an argument of class or enumerated type

根据这个SO帖子中的答案什么是';必须具有类或枚举类型的参数';实际上,这段时间我好像做不到。真的是这样吗?如果没有,我该如何解决此问题或安排变通方法?

我知道我可以做的是将rhs作为std::string,但这项练习的全部要点已经有一半了,因为5*std::string("n")相当笨拙。

来自[over.oper]:

运算符函数应为非静态成员函数或具有至少一个参数,其类型为类、对类的引用、枚举或对枚举

因此,不能重载参数都是内置的运算符。此外,为了找到operator*(int, std::string),它必须在namespace std中,并且向该名称空间添加定义是不正确的。

相反,您可以简单地提供一个小包装:

struct Mult { int value; };

并为其提供过载:

std::string operator*(const Mult&, const char* );
std::string operator*(const char*, const Mult& );

从这里的C++常见问题解答,

C++语言要求您的运算符重载至少占用一个"类类型"或枚举类型的操作数。C++语言将不允许定义所有操作数/参数都为基元类型的。

您应该能够使用用户定义的文字来实现它。例如:

#include <iostream>
#include <string>

std::string operator"" _s(const char* s) { return std::string(s); }
std::string operator"" _s(const char* s, std::size_t len) { return std::string(s, len); }
std::string operator* (unsigned int k, std::string s) {
    std::string t;
    for (unsigned int i = 0; i < k; ++i) 
        t += s;
    return t;
}
std::string operator* (std::string s, unsigned int k) { return k * s; }
int main() {
    std::cout << "Jump!"_s * 5 << "n";
}

您既不能也必须重载该操作;

字符串ctor(2)为您完成的工作

#include <iostream>
#include <string>
int main() {
    std::cout << "here's a message:n" 
              << std::string(5, 'n') 
              << "EOF" << std::endl;
} 

输出:

here's a message:



EOF

(住在Coliru)