【问题标题】:C++ using std::string - why? [closed]C++ 使用 std::string - 为什么? [关闭]
【发布时间】:2019-06-28 10:50:34
【问题描述】:

我想问,

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

#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 overloading 是什么。编辑:std::string ret; 只是一个局部变量。如果这让你感到困惑,那么你很难知道什么是对你来说好的起点,因为很难猜测你实际上已经知道了什么。局部变量声明是一个非常基本的概念。
  • 如果您询问运算符对类的重载,它允许您定义该运算符应用于该类的实例时的行为。在这种情况下,* 被重载,导致std::string 重复包含其预先存在的内容
  • 阅读一本不错的 C++ 书籍。
  • 听起来你可以使用good C++ book
  • @user463035818 请参阅this talk,了解为什么它会成为问题。长话短说,您对 ODR 违规行为敞开心扉。

标签: c++ string function stdstring


【解决方案1】:

通过实现operator*,您可以将size_t 类型与string 类型“相乘”。乘以引号的原因是因为您自己实现了“乘”的含义。在这个特定的实现中,string 只是附加到自身n 次。

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

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 2020-03-28
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多