C++ using std::why?

C++ using std::why?

本文关键字:why std using C++      更新时间:2023-10-16

我想问,

string::string 运算符如何工作,我知道它是一个标准的构造函数,用于使用字符串,但运算符是做什么的?它是否允许我在末尾使用乘数运算符?Size_t表示对象和字符串的大小,并且是通过引用传递的。这些概念有何意义?

#include <iostream>
#include <string>
using namespace std::literals::string_literals;
std::string operator*(std::size_t n, const std::string& s)
{
   std::string ret;
   while (n--)
       ret += s;
   return ret;
}
int main()
{
std::cout << 5 * std::string("Hallo") << std::endl;
std::cout << 5 * "Test"s << std::endl;
}

std::string ret 是什么意思,我可以因为它 std::string 而使用它吗?因为 std::string 在开头就已经定义了 ?

通过实现operator*,你允许类型size_t被"乘"为类型string。 乘以在引号中的原因是因为你实现了自己"乘"的含义。 在此特定实现中,string只是追加到自身 n 次。

所以5 * std::string("Hallo")会导致HalloHalloHalloHalloHallo