C++ using std::why?
C++ using std::why?
我想问,
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
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- Spirit X3, ascii::cntrl why disparity with std::iscntrl?
- Why is std::abs(9484282305798401ull) = 9484282305798400?
- C++ using std::why?
- Why std::string str = {}?
- Why is sizeof(std::mutex)==40 (gcc,clang,icc)?